Python案例:Person类的方法

来自CloudWiki
跳转至: 导航搜索

代码

class Person:
    name="XXX"
    gender="X"
    __age=0#私有属性
    
    def instanceShow(self):#实例方法
        print(self.name,self.gender,self.age)
        
    @classmethod
    def classShow(cls):#类方法
        print(cls.name, cls.gender, cls.age)
        
    @staticmethod
    def staticShow():#静态方法
        print(Person.name, Person.gender, Person.age)

if __name__ == '__main__':
        print(Person.name)#类的属性
        p = Person()#实例的属性
        print(p.name)
        Person.classShow()
        p.instanceShow()