Python basics-encapsulation and extension, static methods and class methods, python static

Source: Internet
Author: User

Python basics-encapsulation and extension, static methods and class methods, python static

I. encapsulation and Expansion

Encapsulation is to clearly distinguish the inside and outside, so that the class implementers can modify the content in the encapsulation without affecting the code of the external caller.External users only know one interface (function). As long as the interface (function) Name and parameters remain unchanged, the user's code will never change. This provides a good foundation for cooperation-or, as long as the Basic Agreement of the interface remains unchanged, the code changes are insufficient.

Instance:

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 attribute, which is closed externally. You can call 7 self. _ length = length 8 self. _ high = high 9 10 def tell_area (self): # The interface provided externally hides the internal implementation details. In this case, we want to return self in Area 11. _ width * self. _ length
1 # user 2> r1 = Room ('bedroom ', 'egon', 20,20, 20) 3 >>> r1.tell _ area () # User call interface tell_area4 400
1 # class designers can easily extend functions, while class users do not need to change their own 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): # provides external interfaces to hide internal implementations. What we want to do now is the volume, and the internal logic has changed, you only need to modify the following line to implement it easily. If the external call is not aware, this method is still used, but the function has changed 11 return self. _ width * self. _ length * self. _ high
1 # for those still using the tell_area interface, you can use the new function 2> r1.tell _ area () 3 8000 without modifying your code.

Ii. Static methods and class methods

Generally, all functions defined in the class(Note: here we are talking about everything. It doesn't matter what self is, And self is just a common parameter.) It is the binding method of the object, when an object calls the binding methodAutomaticPass yourself as the first parameter of the method. In addition, there are two common methods: static and class methods, which are customized for the class. However, if the instance has to be used, no error will be reported.

1. Static Method

It is a common function that is located in the namespace defined by the class and does not operate on any instance type. python provides the built-in function staticmethod to define functions in the class as static methods.

1 class Foo: 2 def spam (x, y, z): # a function in the class. Never be forced, no difference between self and x is that the parameter name is 3 print (x, y, z) 4 spam = staticmethod (spam) # Make the spam function a static method.

Based on the knowledge of the previously learned decorator, @ staticmethod is equivalent to spam = staticmethod (spam), so

1 class Foo: 2 @ staticmethod # decorator 3 def spam (x, y, z): 4 print (x, y, z)

Demo

1 print (type (Foo. spam) # type is essentially a function 2 Foo. spam (, 3) # The call function should have several parameters to pass 3 4 f1 = Foo () 5 f1.spam (, 3) # The instance can also be used, however, static methods are usually used for classes, when the instance is used, the automatic value passing mechanism is lost. 6 7'''8 <class 'function'> 9 2 310 3 311 '''

Application Scenario: many different methods are required to create instances when writing classes. However, we only have one _ init _ function, so static methods can be used in this case.

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 () to generate an instance. The instance uses the current time 9 t = time. localtime () # obtain the structured time format 10 return Date (t. tm_year, t. tm_mon, t. tm_mday) # create an instance and return 11 12 @ staticmethod13 def tomorrow (): # use Date. the instance is generated in the form of tomorrow (). The instance 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 ('20140901', 1987) # custom time 18 B = Date. now () # use the current time 19 c = Date. tomorrow () # Use tomorrow's time 20 21 print (. year,. month,. day) 22 print (B. year, B. month, B. day) 23 print (c. year, c. month, c. day)

2. Class Methods

Class methods are used for classes. When a class is used, the class itself is passed as a parameter to the first parameter of the class method, python has built-in function classmethod for us to define 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 result: 13 <class '_ main __. B '> 214 '''

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. The output result is 22 <__ main __. date object at 0x1013f9d68> 23 '''

Because e is generated using the parent class Date, it does not trigger EuroDate. _ str __. the solution is to use classmethod.

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 Class Method 13 def now (cls): 14 t = time. localtime () 15 return cls (t. tm_year, t. tm_mon, t. tm_mday) # Which class is called, that is, which class cls is used 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 __, at this time e is generated by EuroDate, so the 24 ''' 25 output result will be as expected: 26 year: 2017 month: 3 day: 327 '''

Note: Although static methods and class methods are prepared for classes, they can also be used if the instance is used, but they are easy to confuse when the instance is called, I don't know what you want to do.

1 x = e. now () # The Same can be used to call class methods through instance e, and the static method is also the same as 2 print (x) 3 ''' 4 output result: 5 year: 2017 month: 3 day: 36 '''

 

 

References:

1. http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label10

Related Article

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.