16 Apr 18
1. Encapsulated property
BMI index (bmi is calculated, but obviously it sounds like an attribute rather than a method, it is easier to understand if we make it an attribute)
BMI values for adults:
Too light: below 18.5
Normal: 18.5-23.9
Overweight: 24-27
Obesity: 28-32
very obese, above 32
Body mass index (BMI) = weight (kg) ÷ height ^ 2 (m)
First need to be clear. bmi is calculated, not a fixed value, which means we have to write a function that will immediately calculate a value every time the function is called, but obviously the human bmi value sounds more like a noun than a verb, So we need to add a decorator to the bmi function to disguise it as a data attribute
class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height
@property
def bmi(self):
return self.weight / (self.height * self.height)
be = People ('be', 75,1.80)
print (egon.bmi) # 23.148148148148145
egon.weight=70 #You can change the value for weight, and bmi changes with ˙
print(egon.bmi) #21.604938271604937, the essence of calling egon.bmi is to trigger the execution of the function bmi, so as to get its return value
egon.bmi=123 # Error, the corresponding function behind egon.bmi is a function, so it cannot be assigned
# To understanding
class People:
def __init__(self,name):
self.__name=name
@property
def name(self): #obj.name
print('You are accessing the username...')
return self.__name
@name.setter #obj.name='EGON' # @property decorated functions can drop setters and deleters
def name(self,x):
if type(x) is not str:
raise TypeError('name must be of type str')
self.__name=x
@name.deleter
def name(self):
# print('I won't let you delete')
del self.__name
obj=People('egon')
print(obj.name) #Check
obj.name='EGON' #改
print(obj.name)
obj.name=123 #Restriction change
del obj.name #delete
obj.name
#property, classmethod and staticmethod are the three major functions in object orientation
#Hide the data attribute with the decorator property, and perform the operation of checking, modifying and deleting, and the user does not feel it
2. Polymorphism
What is polymorphism: polymorphism refers to multiple forms of the same thing
Why use polymorphism: Use the base class to create a uniform set of rules and force subclasses to follow (implemented with abstract classes), so that you can directly use the methods under the object without considering the specific type of the object. The performance of polymorphism in the program can be inheritance, but the inheritance of pure meaning cannot make the parent class strictly limit the subclass.
Polymorphism: You can directly use the methods under the object without considering the specific type of the object
How to use polymorphism
import abc #abstract class
class Animal(metaclass=abc.ABCMeta):
@abc.abstractmethod
def eat(self):
pass
@abc.abstractmethod
def drink(self):
pass
@abc.abstractmethod
def run(self):
pass
@abc.abstractmethod
def bark(self):
pass
class Cat(Animal):
def eat(self):
print('cat eat')
def drink(self):
print('cat drink')
def run(self):
print('cat run')
def bark(self):
print('Meow meow meow')
class Dog(Animal):
def eat(self):
print('dog eat')
def drink(self):
print('dog drink')
def run(self):
print('dog run')
def bark(self):
print('Wang Wang Wang')
obj=Animal() # error, the abstract base class itself cannot be instantiated
c=Cat() #When the definition form of the subclass does not meet the requirements, no error will be reported in the definition stage, and an error will be reported when the object of the class definition is called
d=Dog()
c.bark()
d.bark()
or
c=Cat()
d=Dog()
def BARK(animal):
animal.bark()
BARK(c)
BARK(d)
The concept of polymorphism is used all the time in python, and it also brings out the idea that everything is an object in python
s='hello'
l=[1,2,3]
t=(4,5,6)
s .__ len __ ()
l .__ len __ ()
t .__ len __ ()
def LEN (obj):
return obj .__ len __ ()
print (LEN (s))
print (LEN (l))
print (LEN (t))
or
print (len (l))
print (len (s))
print (len)
Three, duck type
class Foo:
def f1(self):
print('from foo.f1')
def f2(self):
print('from foo.f2')
class Bar:
def f1(self):
print('from bar.f1')
def f2(self):
print('from bar.f2')
obj1=Foo()
obj2=Bar()
obj1.f1 ()
obj1.f2()
obj2.f1 ()
obj2.f2()
#In python, looks like a duck, sounds like a duck, is a duck
#Everything in linux is a file, which can be read and written
class Disk:
def read(self):
print('disk read')
def write(self):
print('disk write')
class Txt:
def read(self):
print('txt read')
def write(self):
print('txt write')
class Process:
def read(self):
print('process read')
def write(self):
print('process write')
obj1=Disk()
obj2=Txt()
obj3=Process()
obj1.read()
obj2.read()
obj3.read()
Fourth, classmethod and staticmethod
1 Binding method:
The function defined inside the class is used by the object by default, and it is bound to the object, which is called the binding method of the object. #Do not add any decorators
The method of binding an object is special: it should be called by the object, and when the object is called, the object will be automatically passed in as the first parameter.
The method bound to the class is special: it should be called by the class, the class is called, and the class is automatically passed in as the first parameter. #Add classmethod decorator
In general, functions in a class can be bound to objects, bound to classes (classmethod), or not bound at all (statismmethod)
import settings
class People:
def __init__(self,name,age):
self.name=name
self.age=age
def tell(self):
print('%s:%s' %(self.name,self.age))
@classmethod
def from_conf(cls): #When adding the classmethod decorator, pycharm automatically adds the parameter cls, which is the binding method of the class
return cls(settings.NAME,settings.AGE)
p=People('egon',19)
p.tell()
p4=People.from_conf() #The class call does not need to pass the first parameter, the parameter is automatically passed
p4.tell()
2, staticmethod: non-binding method, is an ordinary function
Features: It is neither bound to a class nor an object, which means that anyone can use it; whoever uses it is an ordinary function, which means that there is no automatic value transfer feature.
import settings
import hashlib
import time
class People:
def __init__(self,name,age):
self.uid=self.create_id()
self.name=name
self.age=age
def tell(self):
print('%s: %s:%s' %(self.uid,self.name,self.age))
@classmethod
def from_conf(cls):
return cls(settings.NAME,settings.AGE)
@staticmethod
def create_id():
m=hashlib.md5()
m.update(str(time.clock()).encode('utf-8')) #time.clock() is related to cpu, each time the value is different
return m.hexdigest()
obj=People('egon',18)
obj.tell() #print(obj.uid,obj.name,obj.age)
print(obj.create_id()) #Object can be called
print(People.create_id()) #Class callable