Python-oriented object-class members

Source: Internet
Author: User

The members of a class can be divided into three main categories: fields, Methods, and properties:

Note: In all members, only the contents of the normal field are saved in the object, that is: how many objects are created based on this class, and how many normal fields are in memory. Other members are saved in the class, that is, only one copy is created in memory, regardless of the number of objects.

(a) field

Fields include: normal fields and static fields, they differ in definition and use, and the most essential difference is that they are saved in memory in different places.

1 classProvince:2     #static fields3Country =" China"4 5     def __init__(self, name):6         #normal field7Self.name =name8 9Obj_henan = Province ("HeNan")Ten  One Print(Obj_hunan.name)#use object access to run that field . A Print(Province.country)#using classes to access static fields

As can be seen from the code above, "Ordinary fields need to access the" static field through the class access, in the use can be seen in the normal field and static field attribution is different. Its content is stored in a similar way as:

by but:

    • Static field saves only one copy in memory
    • Normal fields save one copy of each object

Scenario: When you create an object from a class, you use a static field if each object has the same field

(ii) method

Methods include: Common methods, static methods, and class methods, three methods in memory belong to the class, the difference is that the calling method is different.

    • Normal method: Called by the object ; at least one self parameter; When the normal method is executed, the object that invokes the method is automatically assigned the value to auto;
    • Class method: Called by the class ; at least one cls parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS;
    • Static methods: Called by the class , no default parameters;
1 classFoo:2     def __init__(self, name):3Self.name =name4 5     #normal method, called by the object6     defOrd_fun (self):7         Print(Self.name)8 9     #Static MethodsTen     #The normal method goes through two steps into a static field, 1, removing the parameter self,2, plus the adorner @staticmethod One     #if a method in a class does not have a field in the object (self), the static method can have arguments in addition to self A     #The static method is actually the normal function in the process, the reason is that the method is related to the class . - @staticmethod -     defStatic_func (arg1): the         Print(arg1) -  -     #class Method -     #a special form of a static method that comes with a special parameter CLS, using an adorner @classmethod + @classmethod -     defClass_func (CLS):#CLS = Class +         Print(CLS) A  atObj_foo = foo ("Foo Object") - Obj_foo.ord_fun () -Foo.static_func ("static Func") -Foo.class_func ()

The same point: for all methods, it belongs to the class (non-object), so only one copy is saved in memory.

different points: The method callers are different, and the parameters that are passed in automatically when the method is called are different.

(c) Attributes

To understand the properties of Python, let's look at an example

If we have a student class:

1 class Student (object): 2     def __init__ (self): 3         Self.score = 045 s1 = Student ()6 s1.score = 9999

This assignment S1.score = 9999 This is obviously illogical, score the normal range should be 0-100, in order to limit the scope of score, we may define a set_score() method to set the score, and then through a get_score() To get the results, so that in the set_score() method, you can check the parameters:

1 classStudent (object):2     def __init__(self):3Pass4 5     defSet_score (self, value):6         if  notisinstance (value, int):7             RaiseValueError ("score must be int type")8         elifScore < 0orValue> 100:9             RaiseValueError ("score must between 0-100")Ten         Else: OneSelf.score =value A  -S1 =Student () -S1.set_score (9999)

At this time S1.set_score (9999) will have the following error:

1     Raise ValueError ("score must between 0-100")2 Valueerror:score must Between 0-100

However, the above method of invocation is slightly more complex

Is there a way to set score, which can be used to check parameters, like accessing fields? (Using score = 9999 instead of S1.set_score (9999)), this is a must for a Python programmer who pursues perfection!

Remember the adorner (decorator) can add functionality to a function dynamically? For class methods, adorners work as well. Python's built-in @property decorator is responsible for turning a method into a property invocation:

So we made a change to the Studeng class above:

1 classStudent (object):2     def __init__(self):3         Pass4 5 @property6     defscore (self, score):7         returnSelf.score8 9 @score. SetterTen     defScore (self, value):#The function name is consistent with @property One         if  notisinstance (value, int): A             RaiseValueError ("score must be int type") -         elifValue < 0orValue > 100: -             RaiseValueError ("score must between 0-100") the         Else: -Self.score =value -  -S1 =Student () +S1.score = 9999#use "=" here to access score

The implementation of @property is more complex, we first examine how to use. To turn a getter method into a property, just add @property to it, and at this point, @ The property itself creates another adorner @score.setter, which is responsible for turning a setter method into a property assignment, so we have a controllable attribute operation:

1 Raise ValueError ("score must between 0-100")2 Valueerror:score must Between 0-100

Notice that this magical @property , when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.

You can also define read-only properties, define getter methods only, and do not define setter methods as a read-only property:

1 @property2     defBirth (self):3         returnSelf._birth4 5 @birth. Setter6     defBirth (self, value):7Self._birth =value8 9 @propertyTen     defAge (self): One         return2017-self._birth

The above birth is a read-write property, which age is a readonly property because age it can be calculated based on the birth current time.

@propertyWidely used in the definition of a class, you can let the caller write short code, while ensuring that the parameters are necessary to check, so that the program runs to reduce the likelihood of errors.

Python-oriented object-class members

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.