13. Python's object-oriented advanced article

Source: Internet
Author: User

1. Static method

A static method is a method that can be called directly by a class, similar to a static property, which can be called directly by a class or by an object. Using the adorner @staticmethod in Python to assert that a method is a static method, the instance code for the static method is as follows:

1 classGrade (object):2     def __init__(self,name,count):3Self.__name=name4Self.__count=Count5@staticmethod#assert as a static method6     defPrint_grade ():7         Print("This class is primarily used to create class objects")8Grade = Grade ("Tall (2)", 20)
Grade.print_grade () #通过对象直接调用9Grade.print_grade ()#can be called directly from the class name
2. Class Methods

class methods can also be called by classes and objects, but they can only access class properties, cannot access object properties, and use adorners in Python @classmethod to assert that a method is a class method, the instance code of a class method is as follows:

1 classGrade (object):2     __grade_count= 13     def __init__(self,name,count):4Self.__name=name5Self.__count=Count6@classmethod#assert that only class properties can be accessed for class methods7     defGrade_count (self):8         Print(self.)__grade_count)9 TenGrade.grade_count ()#Call through class OneGrade = Grade ("Freshman (2)", 20) AGrade.grade_count ()#call through Object

I look at the class method and static method seems bad, in fact, in Java or C + + and other high-level languages, only static methods, there is no class method. There must be a reason for the new class method in Python, but I don't know why, but!!! We look closely and find that there are some differences between the two methods:

For static methods, the self parameter is not automatically associated, and the class method is also associated. As for the other differences, I have no idea.

3. Static Properties

in Python, you can turn a method into a property, and sometimes we usually define a property as a private property, and then provide the get and set methods for accessing and assigning a private property, although this is no problem, but it is not as convenient and intuitive to use as the public property. In order for our access to private properties to be as smooth as common attributes, we can do this using adorners @property family.

Existing such a requirement, there is now a student class, whose age is a private attribute, and the age field must meet the following conditions: 1, the user must >0 when modifying, otherwise modified to 0, 2, if the age of 0 o'clock, return 100, 3, if the Age field >0, cannot be deleted, the code is implemented as follows:

1 classStudent (object):2     def __init__(self,name,age):3Self.__name=name4Self.__age= Age5 6 @property7     defAge (self):8         Pass9 @age. SetterTen     defAge (Self,value):#Modify One         ifValue >0: ASelf.__age=value -         Else: -Self.__age=0 the     defprint_selft (self): -         Print("Name:%s, age:%s"% (self.__name, self.__age)) -@age. Getter#Access -     defAge (self): +         ifSelf.__age<=0: -             return100 +         Else: A             returnSelf.__age at@age. deleter#Delete -     defAge (self): -         ifSelf.__age>0: -             Pass -         Else: -             delSelf.__age inStu = Student ("Gao Wenxiang", 18) -Stu.age = 1 to stu.print_selft () + Print(stu.age) - delStu.age the Print(Stu.age)

The property of the adorner has the following 2 points: 1. Turn a method into an attribute 2, wrapping the private attribute with Property.setter, Property.getter, and Property.deleter.

4. Special member Variables

1.__str__: The method that the system calls automatically when the object accesses, we can go to rewrite the __str__ method. The code is as follows:

1 classStudent (object):2     def __init__(self,name,age):3Self.__name=name4Self.__age= Age5     def __str__(self):#overriding base class methods6         returnSelf.__name7Stu = Student ("Gao Wenxiang", 20)8 Print(Stu)#execution Result: Gao Wenxiang

2, __setitem__,__getitem__ and __delitem__: This set of methods can manipulate objects as if they were dictionaries. The code is as follows:

1 classStudent (object):2     def __init__(self):3Self.__info= {}4     def __setitem__(Self, key, value):#Set5Self.__info[Key] =value6     def __getitem__(Self, key):#Assign Value7         returnSelf.__info[key]8     def __delitem__(Self, key):#Delete9         delSelf.__info[key]TenStu =Student () Onestu["name"] ="Gao Wenxiang" A Print(stu["name"]) - delstu["name"] - Print(stu["name"])

3, __new__ Method: __new__ method is called before the initialization, and is called before the __init__ method, and then in the __new__ method to call the __init__ method, the code is as follows:

1 classStudent (object):2     def __init__(self):3         Print("__init__")4     def __new__(CLS, *args, * *Kwargs):5         Print("__new__")6         returnCls.__init__(CLS)7Stu =Student ()8 #Execution Results9 #__new__Ten #__init__

4. Other additions

1 classStudent (object):2     "This is a student class"3     def __init__(self,name,age):4Self.name =name5Self.age = Age6Stu = Student ("Gao Wenxiang", 20)7 Print(Stu.__doc__, Stu.__dict__#执行结果: This is a student class {' name ': ' Gao Wenxiang ', ' Age ': 20}

13. Python's object-oriented advanced 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.