Process python learning notes: Chapter 1, python learning notes
In this chapter, the author briefly introduces the python data model, mainly some special methods of python. For example, _ len __, _ getitem _. describes these methods using a card program.
First, we will introduce the differences between Tuple and nametuple:
Nametuple is similar to the data type of tuples. In addition to being able to access data using indexes, you can also use convenient attribute names to access data.
Traditional tuples are accessed as follows. Access to each element must be indexed. This method is not intuitive.
tup1=('abc','def','ghi')
print tup1[1]
Use nametuple to construct:
tup2=namedtuple('tuple2',['name','age','height'])
t1=tup2('zhf','33','175')
print t1
print t1.age
print t1.height
print t1.name
The result is as follows. In namedtupel, tuple2 is the type name, name, age, and height are the attribute names.
From the above access, we can see that it is more intuitive to directly use the t1.age Method for access. Of course, you can also use indexes such as t1 [0] to access
Namedtupe1 also supports iterative access:
for t in t1:
print t
Like metadata groups, the elements in namedtupel cannot be changed. If t1.age + = 1 is executed. The system will prompt that the element cannot be set.
Traceback (most recent call last ):
File "E:/py_prj/fluent_py.py", line 17, in <module>
T1.age + = 1
AttributeError: can't set attribute
The following is an example of a card in the book. The Code is as follows:
from collections import namedtuple
Card=namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks=[str(n) for n in range(2,11)] + list('JQKA')
suits='spades diamonds clubs hearts'.split()
def __init__(self):
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]
if __name__=='__main__':
deck=FrenchDeck()
print len(deck)
print deck[1]
First, the Card tuples are defined. rank represents the Card number, and suit represents the Card color. Then, the specific meaning of ranks and suit is defined in FrenchDeck. Initialize self. _ cards in _ init.
_ Len _ the length of self. _ cards. _ Getitem _ returns a card value.
The result is as follows: the Card length is 52, where deck [1] is Card (rank = '3', suit = 'spades ')
We can see that len (deck) actually calls the _ len _ method. Deck [1] calls _ getitem __
With the _ getitem _ method, you can perform iterative access as follows:
for d in deck:
print d
Since it can be iterated, we can simulate the random licensing mechanism.
from random import choice
print choice(deck)
Expected result:
Card (rank = '9', suit = 'hearts ')
Next, let's look at another example about vector operations. For example, Vector 1 vector1 (1, 2) and Vector 2 vector2 (3, 4 ). The result of vector1 + vector2 is ). Vector1 and vector2 are both vectors. How can we implement this operation. The method is _ add __,__ mul __
The Code is as follows:
class vector:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __repr__(self):
return '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+other.y
return vector(x,y)
def __mul__(self, scalar):
return vector(self.x*scalar,self.y*scalar)
if __name__=='__main__':
v1=vector(1,2)
v2=vector(2,3)
print v1+v2
print abs(v1)
print v1*3
The calculation result is as follows:
Here _ add __,__ mul __,__ abs _ implements vector addition, multiplication, and modulo operation respectively.
It is worth mentioning the _ repr _ method. This method is called when an object needs to be printed. For example, when print vector (1, 2) is run, the vector (1, 2) is obtained ). otherwise, it indicates the object string: <Vector object at 0x0000>. the functions of _ repr _ and _ str _ are similar.