This chapter mainly describes how to activate some basic object operations in a special way, with the names of these special methods beginning with two underscores, with two underscore endings (such as GetItem), such as Obj[key] behind the getitem method, In order to obtain the value of My_collection[key], the interpreter actually invokes my_collection. GetItem (key).
The example in this chapter is a stack of Python-style cards, very chewy.
1.1 Card Instances
The first example 1-1 establishes a card class:
Import Collections # "1" card
= collections.namedtuple (' card ', [' rank ', ' suit '])
class frenchdeck:# "2"
ranks = [STR (n) for n in range (2, one)] + list (' Jqka ')
suits = ' spades diamonds clubs '. Split ()
def hearts ( Self): # "3"
self._cards = [Card (rank, suit) for suit in self.suits for
rank in self.ranks]
def __len__ (self) : # "4" return
len (self._cards)
def __getitem__ (self, position): # "5" return
Self._cards[position]
"1" collections module, Python has some built-in data types, such as str, int, list, tuple, dict, and so on, the collections module, based on these built-in data types, provides several additional data types:
1.namedtuple (): Generates a tuple subclass that can use a name to access element content
2.deque: Two-terminal queue, which can quickly append and eject objects from the other side
3.Counter: Counter, mainly used to count
4.OrderedDict: Ordered Dictionary
5.defaultdict: A dictionary with default values
Personally, this namedtuple is a bit like a temporary table, where the card in the example is the table name, and rank and suit are the field names.
"2" a dapper class that assigns values to ranks and suits datasets, and reconstructs the init/len/GetItem three methods.
"3" Creates a complete poker instance with Self._cards
"4" calculates the length of the card.
"5" gets the position of each card
Think about it, if you write a pair of similar cards, how much code, and the master code is so simple and efficient.
With the above code, you can easily get a card object, such as:
Deck=frenchdeck ()
print (len (deck))
From a stack of cards to extract a specific piece is also very simple: deck[0] or deck[-1], which 0 is a forward number of the first card, 1 is the reverse number one.
If you want to randomly extract a card is also very simple, with Random.choice, the code is as follows:
From random Import choice
choice (deck)
As you can see, each card is different, this is a random number of wheels (we do not need to generate random numbers and then select the corresponding object, a function to fix), very convenient.
Because the getitem method gives the [] operation to the Self._cards list, our deck class automatically supports slicing, such as looking at the top 3 of a stack of cards and only the cards that look at the card board as a:
Deck[:3]
deck[12::13]# "6"
"6" Here 12 means the index number is 12 card A, the back 13 means every 13 Zhang. It is also easy to display a pair of playing cards, and the iterative deck can be facilitated by a For loop:
In Deck:
print (card)
The reverse iteration is also simple:
For card in reversed (deck):
print (card)
Next to do a slightly more complex operation, sorting, is to use points to determine the size of playing cards, 2 smallest, a maximum, while the largest black peach, Red peach Second, the box again, the smallest plum blossom.
Suit_values=dict (spades=3,hearts=2,diamonds=1,clubs=0)
def spades_high (card):
rank_value= FrenchDeck.ranks.index (Card.rank) # "7"
return Rank_value * Len (suit_values) +suit_values[card.suit]
The following calls the Spades_high function to sort the stacks in ascending order
For card in sorted (Deck,key=spades_high):
print (card)
"7" This piece of code is not a bit difficult to understand, and slowly study. The Rank_value value is equal to the index value of the ranks list below Frenchdeck class (Card.rank), and the card is an object of the card class with rank and suit two attributes.
1.2 How to use special methods
Special methods exist to be invoked by the Python interpreter, and programmers do not have to call these methods directly, which means there is no my_object. Len () This type of writing should use Len (My_object).
This section holds an example of a two-dimensional vector, which is defined by a vector class that reconstructs repr/ABS/bool/Add/Mul These special methods
From math import Hypot
class Vector:
def __init__ (self, x=0, y=0):
self.x = x
self.y = y
def __repr__ ( Self): Return to
' Vector (%r,%r) '% (self.x, self.y)
def __abs__ (self): return
hypot (self.x, Self.y)
def _ _bool__ (self): return
BOOL (ABS (self))
def __add__ (self, Other):
x = self.x + other.x
y = self.y + othe R.y return
vector (x, y)
def __mul__ (self, scalar): return
vector (self.x * scalar, SELF.Y * scalar)
With this class, you can implement vector addition:
V1=vector (2,4)
v2=vector (2,1)
print (V1+V2)
There is no problem invoking the ABS function:
V=vector (3,4)
print (ABS (v))
Note the difference between%r and%s
%r the object with the Rper () method
%s processing an object with the Str () method
In some cases, the results are the same, such as dealing with int objects.
The authors of this book believe that both the Str.format and the format of the strings are used in this book, but the authors prefer to str.format,python programmers preferring%, both of which will continue to coexist.