Class methods and Class properties

Source: Internet
Author: User

The class method exists in order to modify the class properties.

code example:

class people (object):    address = "Shandong"              #类属性    #实例方法    def __init__ (self): = "Xiaowang"         # Instance properties        self.age =                   #实例属性    #类方法    @classmethod    def setnewaddress (CLS):        cls.address = "Inner Mongolia"    #可以通过类名的方式来获取类属性    #但是不能通过类名获取实例属性    #类对象, you can call the Class property directly, or you can call the class method #但是类对象 directly,    disallow the invocation of the instance property, and do not allow the invocation of the instance method    #如果是一个实例对象    #它可以获取实例属性和类属性的值, but only instance properties can be modified, class properties cannot be modified    #他还可以调用实例方法和类方法xiaoming = people () Xiaoming.setnewaddress () print (people.address) execution result: Inner Mongolia

code Example 2:

Class Animal (object):    def __init__ (self, name = "Animal", color = "white"): = name        Self.color = Colorclass Horse (Animal):    horsenum = 0            #类属性    def __init__ (self, name, color = ""):        super (). __INIT__ (name)        Self.sethorsenum ()    @classmethod    def sethorsenum (CLS):        cls.horsenum + = 1bailongma = Horse ("White Dragon Horse") print ( print (bailongma.color) print (bailongma.horsenum) Chituma = Horse ("Red Rabbit Horse") print ( print ( Chituma.color) print (chituma.horsenum) execution result: White Dragon horse white 1 red rabbit horse White 2


Class methods and Class properties

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: 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.