Polymorphic
We write a class named Animal, which has a run () method to print directly:
class Animal (object): def Run (self): Print ('Animal is running ... ')
To understand the benefits of polymorphism, we also need to write a function that takes a variable of type Animal:
def run_twice (animal): animal.run () animal.run ()
When we pass in an instance of animal, Run_twice () prints out:
>>>is running ...
If we define a tortoise type again, derive from Animal:
class Tortoise (Animal): def Run (self): Print ('tortoise is running slowly ... ')
When we call Run_twice (), an instance of the tortoise is passed in:
>>>is running slowly ...
The advantage of polymorphism is that when we need to pass in tortoise, we just have to accept the Animal type, because tortoise is the Animal type, and then you can do it according to the Animal type. Because the Animal type has the run () method, any type passed in, as long as it is a Animal class or subclass, will automatically invoke the actual type of the run () method, which is the meaning of polymorphism.
Class Member
normal field (data attributes): Data attributes is pieces of data held by a specific instance of a class.
static field (class attributes): Python also supports class attributes, which is variables owned by the class itself.
Ordinary objects can only be accessed by objects, static fields should be accessed by the class, and static fields are created when the code is loaded.
Common Methods (instance method)
static Method
Different from the normal method:
1) Remove Self
2) Use @staticmethod adorner
3) A static method called by a class is actually a function, just related to this class
class Method
A class method is a special static method, also called by a class, that differs from a static method:
1) automatically pass in a CLS parameter, the CLS is the function name
class Province: @classmethod def F2 (CLS): print= Province ( ' Henan ' ) hn.f2 ()
The output is: <class ' __main__. Province ' >
Class methods is methods that is not the bound to an object, but to a class!
>>>classPizza (object): ... radius= 42... @classmethod ...defGet_radius (CLS): ...returnCls.radius ...>>> >>>Pizza.get_radius<bound Method Type.get_radius of <class '__main__. Pizza'>>>>>Pizza (). Get_radius<bound Method Type.get_radius of <class '__main__. Pizza'>>>>> Pizza.get_radius isPizza (). Get_radiustrue>>>Pizza.get_radius ()42
Object name Plus () Execute __call__
Class name plus () Execute __init__
comparison of static and class methods :
#!/usr/bin/env pythonclassSmoothie (object): Yogurt= 1Strawberry= 2BANANA= 4MANGO= 8@staticmethoddefBlend (*mixes):returnSUM (MIXES)/len (mixes) @staticmethoddefeternal_sunshine ():returnsmoothie.blend (Smoothie.yogurt, Smoothie.strawberry, Smoothie.banana) @staticmethoddefMango_lassi ():returnSmoothie.blend (Smoothie.yogurt, Smoothie.mango)
With static methods, you need to hardcode class names and use the class method:
#!/usr/bin/env pythonclassSmoothie (object): Yogurt= 1Strawberry= 2BANANA= 4MANGO= 8@staticmethoddefBlend (*mixes):returnSUM (MIXES)/len (mixes) @classmethoddefEternal_sunshine (CLS):returnCls.blend (CLS. Yogurt, CLS. Strawberry, CLS. BANANA) @classmethoddefMango_lassi (CLS):returnCls.blend (CLS. Yogurt, CLS. MANGO)
The first benefit of rational use of class methods is that when you need to change the name of a class, the method of the class does not need to be changed.
Another benefit is that when we create a subclass again,
classBettersmoothie (Smoothie): Yogurt='Yogurt'Strawberry='Strawberry'BANANA='Banana'MANGO='Mango'@staticmethoddefBlend (*mixes):return ', '. Join (mixes)
We have updated the static method blend, the class methods inherited from Smoothie eternal_sunshine () and Mango_lassi () will automatically use the new blend method .
Property:
classPager:def __init__(self, all_count): Self.all_count=All_count @propertydefAll_pager (Self): A1, A2= Divmod (Self.all_count, 10) ifA2 = =0:returnA1Else: returnA1 + 1@all_pager. SetterdefAll_pager (self, value):Print(value) @all_pager. deleterdefAll_pager (self):Print('del All_pager')
Using an adorner @property for a common method is equivalent to constructing a dynamic field that can only be evaluated and cannot be assigned unless the @func_name is used. Setter adorner constructs a function that uses @func_name. deleter Adorners enable properties to be deleted, so that properties have full field properties.
An example:
classCelsius:def __init__(Self, temperature =0): self.set_temperature (temperature)defTo_fahrenheit (self):return(Self.get_temperature () * 1.8) + 32#New Update defget_temperature (self):returnself._temperaturedefset_temperature (self, value):ifValue <-273: RaiseValueError ("temperature below-273 is not possible") Self._temperature= value
Instance variable before adding a ' _ ' means that the field should be a private field, but is still accessible from the outside.
classCelsius:def __init__(Self, temperature =0): Self.temperature=TemperaturedefTo_fahrenheit (self):return(Self.temperature * 1.8) + 32defget_temperature (self):Print("Getting Value") returnself._temperaturedefset_temperature (self, value):ifValue <-273: RaiseValueError ("temperature below-273 is not possible") Print("Setting Value") Self._temperature=Value Temperature= Property (Fget=get_temperature, Fset=set_temperature)
The last line means that the property attaches some code (Get_temperature and Set_temperature) to the Member attribute accesses (temperature). The Get_temperature method instead of a dictionary (__dict__) look-up is automatically executed when trying to get the temperature field of an object.
Super method
classC1:defF1 (self):#print (' c1.f1 ') return123classC2 (C1):defF1 (self):#F1 method for actively executing C2 's parent class #Super (C2,self) is the equivalent of instantiating C1 classRET =Super (C2,self). F1 ()Print('c2.f1') returnRet
The super method can proactively execute a method of the same name as the parent class.
Python 8th Day