Using property() on classmethods

后端 未结 15 918
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:46

    Setting it only on the meta class doesn't help if you want to access the class property via an instantiated object, in this case you need to install a normal property on the object as well (which dispatches to the class property). I think the following is a bit more clear:

    #!/usr/bin/python
    
    class classproperty(property):
        def __get__(self, obj, type_):
            return self.fget.__get__(None, type_)()
    
        def __set__(self, obj, value):
            cls = type(obj)
            return self.fset.__get__(None, cls)(value)
    
    class A (object):
    
        _foo = 1
    
        @classproperty
        @classmethod
        def foo(cls):
            return cls._foo
    
        @foo.setter
        @classmethod
        def foo(cls, value):
            cls.foo = value
    
    a = A()
    
    print a.foo
    
    b = A()
    
    print b.foo
    
    b.foo = 5
    
    print a.foo
    
    A.foo = 10
    
    print b.foo
    
    print A.foo
    

提交回复
热议问题