Python Class Attribute Instance property class method Instance method static method (reprint)

Source: Internet
Author: User



This article is reproduced, purely for the convenience of the back of their own view, suggest or read the original: http://www.cnblogs.com/dolphin0520/archive/2013/03/29/2986924.html



First, let's talk about class properties and instance properties



In the previous example, we were exposed to the class attribute, as the name implies, the class property is the property owned by the class object, it is common to all class object's instance object, there is only one copy in memory, this is a bit similar to the static member variable of class in C + +. For common class properties, they can be accessed from class objects and instance objects outside the class.


class people:
    name = ‘jack’ #public class attribute
    __age = 12 #Private class attribute

p = people ()

print p.name #correct
print people.name #correct
print p .__ age #Error, cannot access private class attributes through instance objects outside the class
print people .__ age #Error, cannot access private class attributes through class objects outside the class


Instance attributes do not need to be explicitly defined in the class, such as:
class people:
    name = ‘jack’

p = people ()
p.age = 12 #Instance properties
print p.name #correct
print p.age #correct

print people.name #correct
print people.age #error
After instantiating the class object people outside the class, an instance object p is generated, and then the sentence p.age = 12 adds an instance attribute age to p, which is assigned a value of 12. This instance attribute is unique to the instance object p. Note that the class object people does not own it (so the age attribute cannot be accessed through the class object). Of course, you can also assign a value to age when instantiating an object.


class people:
    name = ‘jack’
    
    #__ init __ () is a built-in constructor that is called automatically when an object is instantiated
    def __init __ (self, age):
        self.age = age

p = people (12) # constructor initialization
print p.name #correct
print p.age #correct

print people.name #correct
print people.age #error


If you need to modify the class attributes outside the class, you must refer to the class object and then modify it. If you use the instance object to dereference, an instance property with the same name will be generated. Modifying the instance property in this way will not affect the class property. If you later use the instance object to refer to the property with the name, the instance property will be forcibly masked. A class attribute refers to an instance attribute unless the instance attribute is deleted.

class people:
    country = ‘china’
    

print people.country #The output is china
p = people ()
print p.country #The output is china
p.country = ‘japan’
print p.country #The instance attribute will mask out the class attribute with the same name. The output is japan
print people.country #The output is china
del p.country #Delete instance attributes
print p.country #Because the instance attribute has been deleted in the previous step, now only the class attribute is left, so the output is china

Second, look at the difference between class methods, instance methods and static methods
Class method: It is a method owned by a class object. It needs to be marked as a class method with the modifier "@classmethod". For a class method, the first parameter must be a class object, generally "cls" is the first parameter ( Of course, you can use a variable with another name as its first parameter, but most people are used to using 'cls' as the name of the first parameter, and it is best to use 'cls'). You can go through instance objects and class objects. access.
class people:
    country = ‘china’
    
    #Class methods, use classmethod to modify
    @classmethod
    def getCountry (cls):
        return cls.country

p = people ()
print p.getCountry () #You can use the instance object reference
print people.getCountry () #can be referenced by class object


A class method can also be used to modify a class property:


class people:
     country = ‘china’
    
     #Class methods, use classmethod to modify
     @classmethod
     def getCountry (cls):
         return cls.country
        
     @classmethod #Modify class attributes
     def setCountry (cls, country):
         cls.country = country
        

p = people ()
print p.getCountry () #You can use the instance object reference
print people.getCountry () #can be referenced by class object

p.setCountry (‘japan’)

print p.getCountry ()
print people.getCountry () 


Operation Result:






The results show that the access to the class object and the instance object has changed after the class method has been modified for the class property.






Instance method: A member method that is most commonly defined in a class that has at least one parameter and must have an instance object as its first argument, usually with a variable named ' self ' as the first parameter (of course, a variable of a different name as the first argument). An out-of-class instance method can only be called through an instance object and cannot be called by any other means.


class people:
     country = ‘china’
    
     #Instance methods
     def getCountry (self):
         return self.country
        

p = people ()
print p.getCountry () #Correct, you can use the instance object reference
print people.getCountry () #Error, cannot refer to instance method by class object


static methods : modifiers need to be decorated with "@staticmethod", and static methods do not require multiple parameters.


class people:
     country = ‘china’
    
     @staticmethod
     #Static method
     def getCountry ():
         return people.country
        

print people.getCountry () 





For class and instance properties, if a property is referenced in a class method, the property must be a class property, and if a property is referenced in an instance method (unchanged), and a class property of the same name exists, the instance property masks the class property if the instance object has an instance property of the attribute, that is, the instance property is referenced. If the instance object does not have an instance property of that name, then the Class property is referenced, if a property is changed in an instance method, and if there is a class property of the same name, if the instance object has an instance property of the attribute, then the instance property is modified, and if the instance object does not have an instance property of that name, an instance property To modify a class property, if it is outside the class, it can be modified by the class object, and if inside the class, it is only modified in the class method.



From the definition of class and instance methods and static methods, it can be seen that the first parameter of a class method is the class object CLS, which must be the property and method of the class object that is referenced by the CLS, whereas the first argument of an instance method is the instance object self, which can be referred to by self as a class property, It may also be an instance property (which requires a specific analysis), but the instance property has a higher precedence in the case of class properties and instance properties with the same name. There is no need to define additional parameters in a static method, so referencing a class property in a static method must be referred to by the class object.



Python Class Attribute Instance property class method Instance method static method (reprint)


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.