Python Training Day7 Essays

Source: Internet
Author: User

Let's talk about the use of the random module today.

The function of this module is actually random birth number, it is below three methods

Import Randomprint random.random () #默认方法是在0和1之间取一个随机带小数点的随机数print random.randint (#在1和2之间随机取数字), maybe 1 or 2print Random.randrange #在大于等于1切小于2的范围内取随机数, in this case, can only fetch 1 of this value 0.24075696015221

Since random numbers can be taken through the random module, the rules are based on the ASCII code table. In the range from 65 to 127, the case format of the 26 letters from A-y is included. The Chr () function allows you to convert the input number to the corresponding ASCII character.

Import Randomnum=random.randint (65,90) print ' number is%d ASCII was%s '% (NUM,CHR (num)) number is-ASCII is U

The next one is dead. Use the above principle to generate a 4-bit verification code with uppercase letters and 0-9 random numbers

Import random# Create an empty string checkcode= ' #循环4次for I in range (4): Random number between #获取一个0-3 Current=random.randrange (0,4) #如果循环的次数与产    The random number of raw numbers is unequal if current! = I: #就生成一个大写的英文字母 temp=chr (Random.randint (65,90)) #如果循环次数与产生的随机数相等 else: #就产生一个0-9 Random number Temp=random,range (0,9) #不管产生的是字母还是数字都追加到checkcode字符串中 checkcode+=str (temp) #打印字符串 print C HeckcodeEU31


Object oriented

Object-oriented programming has three major features encapsulation, inheritance, polymorphism


Characteristics of the Package

Encapsulation is the fact that multiple functions need to be used to package the parameters into the class, the assignment can be given to other methods have been called.

For example, the following two functions need to call name to complete the output, you need to repeat the name assignment

def sayhi (name): print '%s say hi '%namedef drink (name): print '%s drink water '%namesayhi (' WGW ') drink (' WGW ') WGW say h IWGW Drink water

If we use the encapsulation attribute of the class, the implementation is the following code effect. Just wrap the name inside the class. The method to invoke the class in the future is to implement the printout, no need to re-assign the name.

Class Test_class (): Def __init__ (self,name): Self.name=name def sayhi (self): print '%s say hi '%self.na Me def drink (self): print '%s drink water '%self.nameobj=test_class (' WGW ') Obj.sayhi () Obj.drink () WGW say HIWGW dri NK Water

The above is just a simple example, if we have dozens of functions, each function may have the same parameters as name 3-5. In that case, the object-oriented approach would appear to have a more obvious advantage. The code is more concise.


To invoke the encapsulated name can be called through the object

Class Test_class (): Def __init__ (self,name): Self.name=name def sayhi (self): print '%s say hi '%self.na Me def drink (self): print '%s drink water '%self.nameobj=test_class (' WGW ') #类在实例化的时候会把obj赋值给selfprint Obj.name # This obj.name is actually SELF.NAMEWGW.

Package conditions for Python

A. Multiple methods share a set of variables that are encapsulated in a disguised object

B. Creating multiple objects from a template such as games




Inherited attributes

The

inherits as its name implies, such as the Test_class () class we created above. Later, a TEST_CLASS2 () class was created, and the new class was mainly composed of sports that some characters like to participate in. But we want to be able to say hello to you through the Sayhi () method after entering name in this class. We can then rewrite the Sayhi () method in the new Test_class () class. Of course, this is a very low approach. Then the most efficient is to let test_class2 inherit wgwclass this kind of inside method. Then, in the Wgwclass2, the parent class is used directly.

Class test_class ():     def __init__ (self,name):         self.name=name    def sayhi (self):         print  '%s say hi '%self.name    def drink (self):         print  '%s drink water '%self.nameclass test _class2 (test_class):   #继承父类的方法     def __init__ (self,name,age):         test_class.__init__ (self,name)   #调用父类的__init__方法          self.name=name        self.age=age     def basketball (self):        print  '%s  %d years old like basketball '% (self.name,self.age) obj=test_class2 (' Lucy ', 18) Obj.sayhi () Obj.drink () Obj.basketball ()Lucy say hilucy drink waterlucy 18 years old like basketball 

See new characters through the results Lucy can not only use the basketball method in the subclass, but also inherit the Sayhi () method in the parent class.


Multiple inheritance

Classic class and New class

Classic and modern classes all differ in how they are created

Class Old_class (): #旧式经典类 passclass New_class (object): #新式类, the main thing is to add an object pass when creating

The subclass of the classic class is also the subclass of the classic class and the new class

The main difference between the classical and the new classes is that there is a difference in the way that the parent method is found when multiple inheritance is used. such as the classic class

Class A: #父类是一个经典类 def f (self): print ' This A ' Class B (a): Pass #class B There is no f () method class C (a): Def f (self): print ' This C ' class D (b,c): #class D inherits the B,c two classes Passobj=d () obj.f () #经典类是深度优先, and Class B does not have to go to the B's parent class A to find this a

New class

Class A (object): #父类是一个新式类 def f (self): print ' This A ' class B (a): Pass #class B There is no f () method class C (a): def F (self): print ' This C ' class D (b,c): #class D inherits b,c two classes Passobj=d () obj.f () #新式类是广度优先, class B does not go to the same class C ( Look inside this C

650) this.width=650; "src=" Http://images0.cnblogs.com/blog2015/425762/201508/272315068126604.jpg "alt=" 272315068126604.jpg "/>

However, it is important to note that the so-called depth and breadth priorities are based on the premise that both class B and class C inherit Class A. If class B does not inherit class A then when there is no f () method in Class B, whatever class will go to Class C to find it.


Polymorphic Properties

The teacher said Python1 's polymorphic function is quite poor, and not nearly as much. So basically no practical value.


The above is the three characteristics of object-oriented, the teacher said that in order to increase the force lattice has two points to note:

First, try to use the new class This is the future trend

Second, don't always say the parent class, listen to the earth. To change the base class, the derived class.


How classes and objects are saved in memory

The teacher's argument is that the class and the methods in the class have only one copy in memory, and each object created by the class needs to be stored in memory

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201508/425762-20150829133530437-321533636. JPG "alt=" 425762-20150829133530437-321533636.jpg "/>

Does that sound like a special detour? Simply put, let's say we have a class template called person. Then this template will occupy a portion of memory. Next we created two characters WGW and Lucy with person (). Then each new character is created to occupy a single piece of memory space.


Members of the class

The members of a class are made up of three main parts: Fields, Methods, properties


Field

Normal field

When we create a class, we use the __init__ method to construct the class. and assign the parameter to the self.xxx in fact this self.xxx is the class field, is the ordinary field of the class

Class WGW (): Def __init__ (self,name): Self.name=name #定义一个普通字段obj =WGW (' test ') #实例化print obj.name #通过对象 + field name to To access the normal field test

Static fields

Scenario: When you create an object from a class, you use a static field if each object has the same field

A static field is another layer of reuse

Class WGW (): country= ' China ' #定义静态字段 def __init__ (self,name): Self.name=name print wgw.country #静态字段通过类名 + ground Segment name at the time of the call to China

Normal field belongs to: Object

Static fields belong to: Class

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201509/425762-20150907094454965-329821364. JPG "alt=" 425762-20150907094454965-329821364.jpg "/>


Method static method of ordinary method class method

Common methods

You must have a self parameter when you create it, and assign the object name to self when it is called.

Class WGW (object): Def __init__ (self): Pass Def-Saihi (self): #普通方法, triggered by an object, can add at least one self print ' hi ever Ybody '

Class method

Class WGW (object): Def __init__ (self): Pass def Saihi (self): #普通方法必须有个self print ' Hi everybody ' @cl Assmethod #通过添加classmethod装饰器定义类方法 def saybye (CLS): #类方法, class methods are triggered by assigning the class itself to the CLS incoming method, only one CLS cannot add other parameters to print ' Bye bye ' Wgw.saybye () #通过类名 + method name Call class method

A class method is equivalent to a constraint on a method, and a method can have only one parameter. You do not need to define fields and create objects in Init when calling. Save Memory overhead

Static methods

Class WGW (object): Def __init__ (self): Pass Def-Saihi (self): #普通方法, triggered by an object, can add at least one self print ' hi ever Ybody ' @classmethod #通过添加classmethod装饰器定义类方法 def Saybye (CLS): #类方法, class methods trigger by assigning the class itself to the CLS incoming method, only one CLS cannot add other parameters P Rint ' Bye Bye ' @staticmethod #通过添加staticmethod装饰器定义类方法 def sayhello (name,age): #静态方法, triggered by the class. No need to add self can pass in any parameter print ' Hello ' Wgw.sayhello (' WGW ') #通过类名 + method name Call static method

The use of static methods within a class is equivalent to creating a function in a class. Because you don't have to define fields in Init, you don't have to create objects. Save Memory overhead


Property

The function of a property is to forge a method into a field that has no effect on the result of the operation and the method is the same

A property is also a method that is only modified to be accessed as a field form.

Class WGW (object): Def __init__ (self,name): Self.name=name pass @property #通过添加property装饰器定义将方法定义成属性 def goodboy (self): #属性只能有一个self参数 return ' haha ' obj=wgw (' lala ') print obj.name #调用函数的字段print obj.goodboy #调用设置为属 Goodboy () Method of sexual

From the call method above, the property does disguise a method as a field. and are called in the same way as fields.


Class member Modifiers

Members of the class have been described earlier, including fields, methods, properties

These members also have public members and private members

Normal field

Class WGW (object): Def __init__ (self,name,age): Self.name=name #公有字段 self.age=age def sayhi (self): Print '%s is%d years old '% (self.name,self.age) OBJ=WGW (' lala ') print Obj.name #在类外面直接可以调用obj. Sayhi () Lalalala Ears old

If someone re-assigns a value to a field from outside, it will affect the result of the method's operation

Class WGW (object): Def __init__ (self,name,age): Self.name=name #公有字段 self.age=age def sayhi (self): Print '%s is%d years old '% (self.name,self.age) OBJ=WGW (' lala ') obj.age=30 #在外部可以直接修改字段的值obj. Sayhi () Lala Old #运行的结果被修改了

If you want to prevent this from happening, you can set the field to private

Class WGW (object): Def __init__ (self,name,age): Self.__name=name #在字段名前面加两个下划线表示将该字段设置为私有 self.age=age

When set to private, the field is only called inside the class and cannot be accessed externally. and the derived class of this class can no longer access this field.


Methods and properties can also be set to private, which is also set to private and cannot be accessed by external and derived classes.




This article from "Thunderbolt Tofu" blog, declined reprint!

Python Training Day7 Essays

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.