Using property() on classmethods

后端 未结 15 909
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:49

    Half a solution, __set__ on the class does not work, still. The solution is a custom property class implementing both a property and a staticmethod

    class ClassProperty(object):
        def __init__(self, fget, fset):
            self.fget = fget
            self.fset = fset
    
        def __get__(self, instance, owner):
            return self.fget()
    
        def __set__(self, instance, value):
            self.fset(value)
    
    class Foo(object):
        _bar = 1
        def get_bar():
            print 'getting'
            return Foo._bar
    
        def set_bar(value):
            print 'setting'
            Foo._bar = value
    
        bar = ClassProperty(get_bar, set_bar)
    
    f = Foo()
    #__get__ works
    f.bar
    Foo.bar
    
    f.bar = 2
    Foo.bar = 3 #__set__ does not
    

提交回复
热议问题