I. Packaging and Extension
Encapsulation is a clear distinction between inside and outside, so that the class implementer can modify the encapsulated contents without affecting the external caller's code; while the external user only knows one interface (function), as long as the interface (function) name and parameters remain unchanged, the user's code will never need to change. This provides a good basis for collaboration -- or, as long as the basic convention of interfaces remains unchanged, code changes are not enough to worry about.
Example:
1 #Class Designer 2 class Room: 3 def __init__(self,name,owner,width,length,high): 4 self.name=name 5 self.owner=owner 6 self.__width=width #Private attributes, closed to the outside, class internal callable 7 self.__length=length 8 self.__high=high 9 10 def tell_area(self): #The external interface hides the internal implementation details. At this time, what we want is the area. 11 return self.__width * self.__length
1 #Users 2 >>> r1=Room('Bedroom','egon',20,20,20) 3 >>> r1.tell_area() #User Call Interface tell_area 4 400
1 #Designers of classes easily extend their functions, while users of classes don't need to change their code at all. 2 class Room: 3 def __init__(self,name,owner,width,length,high): 4 self.name=name 5 self.owner=owner 6 self.__width=width 7 self.__length=length 8 self.__high=high 9 10 def tell_area(self): #Externally provided interfaces hide internal implementations. At this point, we want volume.,The internal logic has changed.,Simply modify the following line to make it easy to implement,And external calls are not perceived,This method is still used, but the function has changed. 11 return self.__width * self.__length * self.__high
1 #For those still in use tell_area For interface people, new functions can be used without changing their code at all. 2 >>> r1.tell_area() 3 8000
Static Method and Class Method
Normally, all functions defined in a class (notice, all that's said here, nothing to do with self, self is just a common parameter) are object binding methods, and objects automatically pass themselves as parameters to the first parameter of the method when calling the binding method. In addition, there are two common methods: static method and class method, which are customized for classes, but the examples must be used and will not report errors, which will be introduced later.
1. Static method
It's a common function, located in the namespace defined by the class, and does not operate on any instance type. python built-in the function staticmethod to define functions in the class as static methods.
1 class Foo: 2 def spam(x,y,z): #Never force a function in a class. self and x What's not different is the parameter name. 3 print(x,y,z) 4 spam=staticmethod(spam) #hold spam Function Making Static Method
Based on previous knowledge of decorators, @static method is equivalent to spam = static method (spam), so
1 class Foo: 2 @staticmethod #Decorator 3 def spam(x,y,z): 4 print(x,y,z)
Use demonstrations
1 print(type(Foo.spam)) #The essence of type is function. 2 Foo.spam(1,2,3) #Calling a function should pass several parameters with just a few parameters 3 4 f1=Foo() 5 f1.spam(3,3,3) #Instances can also be used,But usually static methods are for classes,Instances lose the mechanism of automatic value transfer in use 6 7 ''' 8 <class 'function'> 9 2 3 10 3 3 11 '''
Application scenario: There are many different ways to create instances when writing classes, and we have only one _init_ function, so static methods come in handy.
1 class Date: 2 def __init__(self,year,month,day): 3 self.year=year 4 self.month=month 5 self.day=day 6 7 @staticmethod 8 def now(): #use Date.now()Form to produce examples,This example uses the current time 9 t=time.localtime() #Getting structured time formats 10 return Date(t.tm_year,t.tm_mon,t.tm_mday) #New instance and return 11 12 @staticmethod 13 def tomorrow():#use Date.tomorrow()Form to produce examples,This example uses tomorrow's time. 14 t=time.localtime(time.time()+86400) 15 return Date(t.tm_year,t.tm_mon,t.tm_mday) 16 17 a=Date('1987',11,27) #Define your own time 18 b=Date.now() #Use the current time 19 c=Date.tomorrow() #Take tomorrow's time 20 21 print(a.year,a.month,a.day) 22 print(b.year,b.month,b.day) 23 print(c.year,c.month,c.day)
2. Class Method
Class methods are used by classes, which pass the class itself as the first parameter to the class method. python has built-in function classmethod to define the functions in the class as class methods.
1 class A: 2 x=1 3 @classmethod 4 def test(cls): 5 print(cls,cls.x) 6 7 class B(A): 8 x=2 9 B.test() 10 11 ''' 12 Output results: 13 <class '__main__.B'> 2 14 '''
Application scenarios
1 import time 2 class Date: 3 def __init__(self,year,month,day): 4 self.year=year 5 self.month=month 6 self.day=day 7 8 @staticmethod 9 def now(): 10 t=time.localtime() 11 return Date(t.tm_year,t.tm_mon,t.tm_mday) 12 13 class EuroDate(Date): 14 def __str__(self): 15 return 'year:%s month:%s day:%s' %(self.year,self.month,self.day) 16 17 e=EuroDate.now() 18 19 print(e) #Our intention is to trigger. EuroDate.__str__,But the result is 20 ''' 21 Output results: 22 <__main__.Date object at 0x1013f9d68> 23 '''
Because e is generated with the parent class Date, it will not trigger EuroDate. _str_ at all. The solution is to use the class method.
1 import time 2 class Date: 3 def __init__(self,year,month,day): 4 self.year=year 5 self.month=month 6 self.day=day 7 # @staticmethod 8 # def now(): 9 # t=time.localtime() 10 # return Date(t.tm_year,t.tm_mon,t.tm_mday) 11 12 @classmethod #Change to Classification Method 13 def now(cls): 14 t=time.localtime() 15 return cls(t.tm_year,t.tm_mon,t.tm_mday) #Which class to call,Which class to use? cls To instantiate 16 17 class EuroDate(Date): 18 def __str__(self): 19 return 'year:%s month:%s day:%s' %(self.year,self.month,self.day) 20 21 e=EuroDate.now() 22 23 print(e) #Our intention is to trigger. EuroDate.__str__,here e That's why EuroDate Produced,So it will be as we wish. 24 ''' 25 Output results: 26 year:2017 month:3 day:3 27 '''
Attention should be paid to static methods and class methods. Although they are prepared for classes, they can also be used if instances are used. However, when instances are invoked, they are easily confused and do not know what you want to do.
1 x=e.now()# Calling class methods through instance e can also be used, as can static methods. 2 print(x) 3 ''' 4 Output results: 5 year:2017 month:3 day:3 6 '''
Reference material:
1. http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label10