Process python learning notes: Chapter 1, python learning notes

Source: Internet
Author: User

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.

print tup1[1]

Use nametuple to construct:

print t1
print t1.age
print t1.height
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/", 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


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__':
    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):
    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):
        return vector(x,y)
    def __mul__(self, scalar):
        return vector(self.x*scalar,self.y*scalar)
if __name__=='__main__':
    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.




Related Article

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: 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.