0
点赞
收藏
分享

微信扫一扫

python @property,@staticmethod,@classmethod 使用例子

王栩的文字 2023-04-26 阅读 58


1,代码 

#coding=utf-8

class MyClass(object):
    def __init__(self):
        print 'init'
        self._name = 'the5fire'

    @staticmethod
    def static_method():
        print 'This is a static method!'

    @classmethod
    def class_method(cls):
        print 'This is a class method',cls
        print 'visit the property of the class:',cls.name
        print 'visit the static method of the class:',cls.static_method()
        instance = cls()
        print 'visit the normal method  of the class:',instance.test()

    def test(self):
        print 'call test'

    @property
    def name(self):
        return self._name
    @name.setter
    def name(self,name):
        self._name=name  
    
if __name__ == '__main__':
    MyClass.static_method()
    MyClass.class_method()
    mc = MyClass()
    print mc.name
    mc.name = 'huyang'
    print mc.name




输出

This is a static method!
This is a class method <class '__main__.MyClass'>
visit the property of the class: <property object at 0x00B935A0>
visit the static method of the class: This is a static method!
None
init
visit the normal method  of the class: call test
None
init
the5fire
huyang




举报

相关推荐

0 条评论