Using property() on classmethods

后端 未结 15 941
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:37

    Because I need to modify an attribute that in such a way that is seen by all instances of a class, and in the scope from which these class methods are called does not have references to all instances of the class.

    Do you have access to at least one instance of the class? I can think of a way to do it then:

    class MyClass (object):
        __var = None
    
        def _set_var (self, value):
            type (self).__var = value
    
        def _get_var (self):
            return self.__var
    
        var = property (_get_var, _set_var)
    
    a = MyClass ()
    b = MyClass ()
    a.var = "foo"
    print b.var
    

提交回复
热议问题