Process Python Learning notes: Chapter One

Source: Internet
Author: User

In this chapter, the author briefly introduces the Python data model, mainly Python's special methods. Like __len__, __getitem__. and use a card program to explain these methods.

First, we introduce the difference between the following tuple and Nametuple:

Nametuple are data types that are similar to tuples. In addition to being able to access data with an index, it also supports access to data with convenient property names.

The traditional tuple access is as follows. Access to each element must be found through the index. This is a very non-intuitive way to find

tup1= (' abc ',' def ',' Ghi ')
TUP1[1]

Use Nametuple to construct:

Tup2=namedtuple (' tuple2 ', [' name ', ' age', 'height '])
T1=tup2 (' ZHF ','a ', '175')
T1
T1.age
T1.height
T1.name
The results are as follows, Tuple2 is the type name in Namedtupel, Name,age,height is the property name
From the above access can be seen, directly with T1.age method access more intuitive. Of course, you can also use indexes such as t1[0] method to access

Namedtupe1 also supports iterative access:

T1:
T
As with tuples, the elements in the Namedtupel are not changeable. If the t1.age+=1 is executed. You will be prompted not to set the element

Traceback (most recent):

File "e:/py_prj/fluent_py.py", line +, in <module>

T1.age+=1

Attributeerror:can ' t set attribute

Here's an example of a card in the book, with the following code:

Namedtuple

Card=namedtuple (' Card ', [' rank ',' suit ')

Frenchdeck:
Range (2,11)] + list (' Jqka ')
suits=' Spades Diamonds Clubs Hearts '. Split ()
__init__ (self):
Self.ranks]
__len__ (self):
Len (self._cards)
__getitem__ (self, position):
Self._cards[position]

__name__==' __main__ ':
Deck=frenchdeck ()
Len (deck)
DECK[1]

The first defined card, rank represents the number of cards, suit represents the card suit. Then in the Frenchdeck first defined the ranks and suit specific points. Initializes the self._cards in __init__.

__len__ the length of the feedback self._cards. __getitem__ feedback the specific card value.

As a result, the card length is 52, where deck[1] is card (rank= ' 3 ', suit= ' spades ')

You can see that Len (deck) actually calls the __len__ method. DECK[1] is called __getitem__

Because of the __getitem__ method, iterative access is possible, as follows:

Deck
D

Since it is iterative, we can simulate the mechanism of random licensing.

Choice
Choice (deck)

Get results:

Card (rank= ' 9 ', suit= ' hearts ')

Next look at another example, about vector operations. For example, there are vectors 1 Vector1, 2 vector2 (3,4). Then the result of Vector1+vector2 should be (4,6). Vector1 and Vector2 are vectors, how do they work? Method is __add__,__mul__

The code is as follows:

classVector
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):
returnHypot (SELF.X,SELF.Y)
def__bool__ (self):
returnBOOL (ABS (self))
def__add__ (Self,other):
X=self.x+other.x
Y=self.y+other.y
returnVector (x, y)
def__mul__ (self, scalar):
returnVector (Self.x*scalar,self.y*scalar)
__name__==' __main__ ':
V1=vector (ON)
V2=vector (2,3)
V1+v2
ABS (v1)
V1*3

The results of the operation are as follows:

Here __add__,__mul__,__abs__ the addition of vectors, multiplication, and the operation of modulo.

It is worth mentioning that the method of __repr__. This method is called when the object needs to be printed. For example, when the print vector (in) gets the vector. Otherwise, it is the string representing the object: <vector object at 0x0000>. The role of this __repr__ and __str__ is similar

Process Python Learning notes: Chapter One

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.