In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn Python technology". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to learn Python technology.
Collection.len () is written in an object-oriented language, and len (collection) is written in the Python language. This style is called Pythonic. From the former to the latter, just like doing magic, it brightens people's eyes for a moment. This trick is the Python magic method, or double-underscore method, which is a special method that starts with a double underscore and ends with a double underscore, such as obj [key]. The Python interpreter is actually converted to obj.__getitem__ (key) to run, but the user is not aware of it.
_ _ getitem__ and _ _ len
_ getitem__ is used to obtain data, and _ _ len__ is used to return length. These two magic methods are the basis of Python, which we can learn from a deck of playing cards:
Import collections # define a deck Card = collections.namedtuple ('Card', [' rank', 'suit']) class FrenchDeck: # size ranks = [str (n) for n in range (2,11)] + list (' JQKA') # pattern suits = 'spades diamonds clubs hearts'.split () def _ init__ (self): # generate a deck self._cards = [Card (rank) Suit) for suit in self.suits for rank in self.ranks] def _ len__ (self): return len (self._cards) def _ getitem__ (self, position): return self._ cards [position]
We couldn't do anything about this deck, but with the implementation of _ _ len__, we can use the len () function to see how many cards there are:
> > len (deck) 52
Because of the implementation of _ _ getitem__, you can use parentheses to index values:
> deck [0] Card (rank='2', suit='spades')
Ability to slice:
> > deck [: 3] [Card (rank='2', suit='spades'), Card (rank='3', suit='spades'), Card (rank='4', suit='spades')] > deck [12 rank='2', suit='spades' 13] [Card (rank='A', suit='spades'), Card (rank='A', suit='diamonds'), Card (rank='A', suit='clubs'), Card (rank='A', suit='hearts')]
Ability to iterate:
For card in deck: # doctest: + ELLIPSIS... Print (card) Card (rank='2', suit='spades') Card (rank='3', suit='spades') Card (rank='4', suit='spades').
Have you found that the magic method can be used to install B? Others can only write a class get, set, you can write a class can also show off skills, 666.
The Python magic method is used by the Python interpreter and generally does not need to be called directly. Python will adjust it itself. For example, writing len (my_object) as my_object.__len__ () is self-defeating.
Magic method implementation operator
The previous example implements the value and length, then take a look at another example, using _ _ repr__, _ _ abs__, _ _ bool__, _ _ add__, _ _ mul__, to implement the operators:
From math import hypot # two-dimensional vector class Vector: def _ _ init__ (self, x _ init__, y _ vector 0): self.x = x self.y = y # expression def _ _ repr__ (self): return 'Vector (% r,% r)'% (self.x, self.y) # absolute def _ _ abs__ (self): return hypot (self.x Self.y) # Boolean def _ bool__ (self): return bool (abs (self)) # Additive def _ add__ (self, other): X = self.x + other.x y = self.y + other.y return Vector (x, y) # multiplicative def _ mul__ (self, scalar): return Vector (self.x * scalar Self.y * scalar)
_ _ add__ implements addition:
> v1 = Vector (2,4) > > v2 = Vector (2,1) > v1 + v2 Vector (4,5)
_ _ abs__ implements the absolute value:
> v = Vector (3,4) > abs (v) 5.0
_ _ mul__ implements multiplication:
> > v * 3 Vector (9,12)
_ _ repr__ implements the string representation of the object:
Vector (4,5)
Otherwise, the resulting string could be.
_ _ bool__ implements a Boolean value:
If Vector (4,5): return True
Other magic methods
There is no end to magic methods in one article, and we will continue to explore how to use and implement them in subsequent articles.
Tips
This section is what I recorded when I watched "fluent Python" for the first time:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Collections.namedtuple can be used to create objects with only a few properties but no methods, such as
Hongmeng official strategic cooperation to build-- HarmonyOS technology community beer_card = Card ('7pm,' diamonds')
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The difference between 2.random.choice and random.sample is that sample is the return sequence and choice is the return element, so when using sample (list, 1) [0], it is better to use choice (list) directly.
Special methods exist to be called by the Python interpreter.
PyVarObject is a C language structure that represents built-in objects of variable length in memory. The _ _ len__ of list or str or bytearray actually returns the PyVarObject.ob_size property, which is much faster than calling a method.
The reason why len is not a common method is to allow the data structures that come with python to go through the back door, and the same goes for abs.
Many times the purpose of calling the _ _ init__ method is to call the superclass's constructor in the _ _ init__ method of your own subclass.
Abs, which returns the absolute value of the input value if the input is an integer or floating-point number, and the module of the complex number if the input is complex.
If you choose between _ _ repr__ and _ _ str__, _ _ repr__ is better, because if an object does not have a _ _ str__ function, the interpreter will use _ _ repr__ instead.
One of the basic requirements of a python object is that it has a reasonable string representation, which is why there are special methods _ _ repr__ and _ _ str__ in the data model.
To determine whether a value x is true or false, python calls bool (x), which is backed by a call to x.destroy fake bool _ (). If it does not exist, x.roomloose _ () is called, returning 0 as Flase and non-0 as True.
Python provides a rich set of numeric types through operator overloading, including decimal.Decimal and fractions.Fraction in addition to the built-in ones.
At this point, I believe you have a deeper understanding of "how to learn Python technology". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.