Using property() on classmethods

后端 未结 15 942
Happy的楠姐
Happy的楠姐 2020-11-22 16:55

I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() functi

15条回答
  •  甜味超标
    2020-11-22 17:27

    I hope this dead-simple read-only @classproperty decorator would help somebody looking for classproperties.

    class classproperty(object):
    
        def __init__(self, fget):
            self.fget = fget
    
        def __get__(self, owner_self, owner_cls):
            return self.fget(owner_cls)
    
    class C(object):
    
        @classproperty
        def x(cls):
            return 1
    
    assert C.x == 1
    assert C().x == 1
    

提交回复
热议问题