Static properties for Class 1.1, class methods, static methods for classes 1.1.1 static properties (@property)
In the class:
Python's built-in @property decorator is responsible for invoking a method (function) into a property.
Class Student: def __init__ (self,name,age,score): self.name = name Self.age = Age Self.score = Score @property def get_score (self): return Self.score def learn (self): return self.names1 = Student ( "Xiaoming", 12,88) print (s1.get_score) #使用的 @property Property Call, short function code print (S1.learn ()) #原来方法的调用 # S1.get_score = #不能修改该属性用了 @property # s1.learn = #可以修改该函数属性 useless @property# Note @property is widely used in the definition of classes, allowing callers to write short code.
You can encapsulate the logic of a function so that when the user calls it, the function's method looks like a normal property.
1.1.2 class Method (@classmethod)
Class Kls: Money = ten def __init__ (Self,money): self.init = money + @classmethod def get_no_of_ Instance (CLS): #cls应该是传入的一个类名 # Print (Cls.money) is equivalent to #print (Kls.money) return cls.moneys1 = Kls (12 ) #类实例化一个对象print (s1.init) #查看实例属性的变量init的值print (S1.money) #查看类属性的变量Kls. Get_no_of_instance () s1. Get_no_of_instance () #这里的调用, the class to which the instance belongs will be passed in # Note: Here is the method that the class is calling itself, with no relation to the instance
@classmethod class method, but only for class use (whether or not an instance exists), access only the instance variable
1.1.3 static method (@staticmethod)
There are often some functions that are related to a class, but you need to use static methods, such as changing the properties of other classes, at run time without the need for instances and classes to participate.
Class Kls: Money = ten def __init__ (Self,money): self.init = money + @classmethod def get_no_of_ Instance (CLS): #cls应该是传入的一个类名 # Print (Cls.money) is equivalent to #print (Kls.money) return Cls.money @ Staticmethod def test (x, y): print (x, y) #这跟类的变量, and instance variable it's okay. return x, y def do (self): Print ("Self" is passed in here) S2 = Kls (s2.test) kls.test (11,22)
@staticmethod is only nominally the management of the attribution class and cannot use variables of class and instances, just the toolkit of classes, seldom used.
1.2 Class combinations
For example: Define a person's class, people have head, torso, hands, feet and other data properties, these properties can be instantiated through a class object, which is the combination.
Combination use:
1: Make a connection
2: The small composition of the large
Class Hand: passclass Foot: passclass Trunk: passclass Head: passclass Person: def __init__ (self , Id_num,name,hand,foot,trunk,head): self.id_num=id_num self.name=name self.hand=hand () Self.foot=foot () self.trunk=trunk () self.head=head ()
Cases:
Class School:def __init__ (self,name,addr): self.name = name self.addr = addr def tell_info (self): Print ("Shcool%s%s"% (SELF.NAME,SELF.ADDR)) class Course:def __init__ (Self,name,price,period,school): self. Name = Name Self.price = Price Self.period = Period Self.schoool = Schoolclass tearcher:def __ini T__ (self,name,hobby,school): self.name = name Self.hobby = Hobby Self.school = SCHOOLS1 = School ("PKU "," Beijing ") s2 = School (" Shang Da "," Shanghai ") s3 = School (" significant "," chongqing ") info =" "" 1 Peking University Beijing Campus 2 Shanghai Campus 3 major Shenzhen Campus "" "While True:print (info) menu = {"1": S1, "2": S2, "3": s3,} choice = input ("Please select school >>:") School_obj = Menu[choi CE] name = input ("course name >>:") Price = Input ("Course price >>:") period = input ("course period >>:") Tname = input ( "Teacher name >>") Thobby = input ("Teacher hobby >>") Teacher_obj = Tearcher (tname,thobby,school_obj) New_course = Cours E (Name,price,period,school_obj) Print ("%s" Teacher "hobby"%s "course"%s "price"%s "period"%s "campus"%s "address"%s "% (Teacher_obj.name,teacher_obj.hobby, n Ew_course.name,new_course.price,new_course.period, SCHOOL_OBJ.NAME,SCHOOL_OBJ.ADDR))
1.3 Object-oriented programming three major features
1. Inheritance
2. Encapsulation
3. polymorphic
1.3.1 Inheritance
Class inheritance: Like the parent, child, and inheritance relationships in life, the parent class is also called the base class.
The inheritance of classes in Python is divided into: single inheritance and multiple inheritance
Class ParentClass1: #基类 passclass ParentClass2: #基类 Pass class Subclass (PARENTCLASS1): #单继承 Subclass Passclass Subclass (PARENTCLASS1,PARENTCLASS2): #多继承 Subclass (subclass) Pass
1.3.2 inheritance inherits what property of the parent class
The essence of inheritance is that the parent class passes its own property reference to the child class, and the subclass can invoke the property of the parent class, in fact the parent's property is not the son's
So. Any data property and function attribute defined in a subclass are present in the properties of the subclass, and are called first from the property Dictionary of their own.
Class Father: Money = #父类自已有100 def __init__ (self): pass def Teach (self): print (" Teach son ") class Son (Father): Money = 9999999 #儿子通过发展的9999999s1 = Son () print (S1.money) #子类自已的属性s1. Teach () #子类调用父类的方法
1.3.3 When to use inheritance
1. When there are significant differences between classes, and the smaller classes are the components required for larger classes, the combination is preferable
For example: Describe a robot class, the big class of robots is composed of a lot of unrelated small classes, such as mechanical arms, legs, body, battery class
2. When there are many identical functions between classes, extracting these common functions into a base class, with better inheritance
For example:
Cats can: Meow meow, eat, drink, pull, sprinkle
Dogs can: bark, eat, drink, pull, sprinkle
If we were to create a class for both cats and dogs, we would need to implement all of their functions for cats and dogs, as shown here:
Class Cat: def meow meow (self): print ' Meow meow ' def eat (self): # do something def drink (self): # do something def Pull (self): # do something def Caesar: # do Somethingclass dog: def barking (self): print ' meow meow ' def Eat ': # do something def drink (self): # do something def pull (self): # do something def scatter (self): # do something pseudo code
The above code is not difficult to see, eat, drink, pull, and Satan is the function of both cats and dogs, and we are the cat and the dog's class has been written two times. If you use the idea of inheritance, implement as follows:
Animals: Eating, drinking, pulling, spreading
Cat: Meow Meow (cat inherits function of animal)
Dog: Barking (dogs inherit the function of animals)
Class Animal: def Eat (self): # do something def drink (self): # do something def pull (self): # do Something
def: # do something# write another class name in parentheses after the class, indicating that the current class inherits another class Cat (animal): def meow meow (self ): print (' Meow meow ') # Write another class name in parentheses after the class, indicating that the current class inherits another class dog (animal): def Barking (self): print ("bark") pseudo-code
Implementation of inheritance
#!/usr/bin/env python#-*-coding:utf-8-*-class Animal: def Eat (self): print ("%s eat"%self.name) def drink ( Self): print ("%s drink"%self.name) def shit (self): print ("%s pull"%self.name) def pee (self): print ("% s Caesar "%self.name" class Cat (Animal): def __init__ (self, name): self.name = name self.breed = ' cat ' def Cry (self): print (' Meow meow ') class Dog (Animal): def __init__ (self, name): self.name = name self.breed= ' dog ' def Cry (self): print (' barking ') # ######### performs ######## #c1 = Cat (' Black Cat ') c1.eat () C2 = Cat (' White Cat ') c2.drink () D1 = Dog (' II ha ') d1.eat () d1.cry ()
Inheritance has two meanings at the same time:
1. Inherit the method of the base class and do it from the changes or extensions (code reuse)
2. Declare that a subclass is compatible with an accumulation, define an interface class, subclass inherits the interface class, and implements the method defined in the interface.
However, in practice, the first meaning of inheritance is not very large, or even often harmful, because it makes the subclass and accumulation appear strong coupling.
The second function of inheritance is very important, also called "Interface Inheritance"
Interface inheritance is essentially a requirement to make a good abstraction, which prescribes a compatible interface so that external callers do not need to be concerned with specific details. All objects of a particular interface are treated in a non-discriminatory time frame. This kind of programming, called normalization.
Inheritance order of the 1.3.4 class
Above is the order of inheritance for classes in Python2
Inheritance order of classes in Python3
#!/usr/bin/env python#-*-coding:utf-8-*-class A: def Test (self): print ("a") class B (a): # def test (self): # print ("B") passclass C (A): def Test (self): print ("C") class D (B): # def test (self): # print ("D") passclass E (C): def Test (self): print ("E") class F (d,e): # def test (self): # print ("F") PASSF = f () f.test () # Print (F.mro ()) print (f.__mro__) #python3中类继承顺序:f->d->b-> E->c->a
#python2经典类继承顺序: f->d->b->a->e->c Python2 Classic class, need to switch to Python2 interpreter
The order in which Python inherits classes. is inherited based on the analysis of the MRO.
This MRO list is a simple list of all the accumulated linear sequences.
To implement inheritance, Python finds the base class from left to right on the MRO list until the first class that matches the property is found.
The MRO list of all the parent classes is followed by the following three guidelines:
1. Subclasses are checked before the parent class
2. Multiple parent classes are checked according to their order in the list
3. If there are two valid choices for the next class, select the first parent class
Methods for calling a parent class in a 1.3.5 subclass
The subclass inherits the method of the parent class and then wants to modify it. Note: Based on the original modification, it is necessary to call the parent class's method in the subclass.
Method One: Parent class name. Parent class Method ()
Class Vehicle: # defines the vehicle class parent class country = ' China ' def __init__ (self, name, speed, load, power): Self.name = name self.speed = Speed self.load = load self.power = Power def run (self): print (' Start ... ') class Subway (Vehicle): # Metro Sub def __init__ (self, name, speed, load, power, line): vehicle.__ Init__ (self, name, speed, load, power) #父类的属性 self.line = line def run: print (' Welcome to Metro '%s '% self.li NE) vehicle.run (self) #子类中调用父类的方法line13 = Subway (' China metro ', ' 180m/s ', ' 1000 people/box ', ' electricity ', ') Line13.run ()
Method two: Super ()
Class Vehicle: #定义交通工具类 country= ' China ' def __init__ (self,name,speed,load,power): #注 self.name= Name self.speed=speed self.load=load self.power=power def run (self): print (' Activate ... ') class Subway (Vehicle): #地铁 def __init__ (self,name,speed,load,power,line): #super (subway,self) is equivalent to the instance itself Super (Subway,self). __init__ (Name,speed,load,power) #注: Calling the properties of the parent class Self.line=line def run (self): print (' Metro%s ' welcome you '%self.line ') Super (Subway,self). Run () #子类调用父类的方法supperline13 =subway (' China metro ', ' 180m/s ', ' 1000 people/box ', ' electricity ', ') Line13.run ()
When you use the super () function, Python continues to search for the next class on the MRO list. As long as each redefined method uses super () and only calls it once, the control flow will eventually traverse the complete MRO list, and each method will only be called once.
1.4 polymorphic
What is polymorphic
The inheritance of a class has two meanings: changing the extension
Polymorphism is a concrete implementation mechanism of the two layers meaning of the class. That is, invoking a different class instantiation gets the same method under the object. The process of implementation is different.
The standard type in Python is a good example of a polymorphic concept such as (str.__len__ (), list.__len__ (), tuple.__len__ can Len (str), Len (list), Len (tuple))
Polymorphism is actually dependent on the two meanings of inheritance: "Change" and "extension" itself means there must be a mechanism to automatically select the version you have changed/extended, so there is no polymorphism, then two meanings can not be achieved.
Therefore, polymorphism is essentially the implementation detail of inheritance, so it is clearly illogical to make polymorphism and encapsulation and inheritance two concepts parallel.
1.5 Package
What is encapsulation: in the case of life, the pack is like a sack, used to store items, the seal is the sack of the seal.
In object-oriented, the sack is a class or object, with data attributes and function attributes in it, and for classes and objects, the encapsulated concept is hidden.
Cases:
is the property and method in the class that defines the private, which is used only inside the class and cannot be accessed externally.
Python does not rely on language features to achieve a second level of encapsulation, but rather by following certain data attributes and function attributes of the naming convention to achieve the effect of the closure
Convention one: Any name that starts with a single underscore should be internal, private.
class people: _star= ' earth ' def __init__ (self,id,name,age,salary): self.id=id Self.name=name self._age=age self._salary=salary def _get_id (self): print (' I am a private method ah, I found the ID is [%s] '%self.id) # We clearly agreed, as long as the attribute before adding a single underline, then he belongs to the internal properties, can not be called outside the Ah, why can also call??? Print (People._star) p1=people (' 3706861900121221212 ', ' YJ ', 18,10) print (p1._age,p1._salary) p1._get_id ()
The above private _ Property: can also be accessed.
Python does not really prevent you from accessing private properties, which is just a convention.
Convention two: The name of a double-underlined beginning
class people: __star= ' earth ' #私有 star = "Moon" #共有 def __init__ (self,id,name,age,salary): Self.id=id self.name=name self.__age=age #私有 self._salary=salary #私有 def _get_id (self): print (' I am a private method ah, I found the ID is [%s] '%self.id) p1=people (' 333333 ', ' Xixi ', 18,10) print (People.star) #能访问print (p1._ Salary) #能访问print (People.__star) #不能访问
How private properties can be accessed:
Cases:
Class Site:def __init__ (self, Name, URL): self.name = name # publicself.__url = URL # privatedef The Who:p rint (' Name : ', self.name ' Print (' URL: ', Self.__url) def __foo (self): # Private method Print (' This is Private method ') def foo (self): # Public method Print (' This is public method ') Self.__foo () # Print (site.__dict__) x = Site (' Baidu ', ' www.baidu.com ') print (x.__dict__) # View the object's Properties dictionary print (x._site__url) #通过属性字典调用私有方法 # Print (site.__dict__) #查看类的属性字典x. _site__foo ()
Why do I have access to private properties?
Python does not fundamentally restrict your access. The reason Python is so designed is that Python makes a non-rigid package that avoids our misuse of encapsulation.
Encapsulation is the explicit distinction between inside and outside, so that the class implementation can modify the contents of the package, without affecting the external callers, while the external caller can also know that they can not touch where. This provides a good basis for cooperation--or, as long as the interface's underlying contract is unchanged, the code changes anthias.
Python Object-oriented two