Python property returning property object

后端 未结 4 1844
别跟我提以往
别跟我提以往 2021-02-19 02:57

I have a class like this:

class Foo(object):
    def __init__(self):
        self.bar = property(self.get_bar)

    def get_bar(self):
        return \"bar\"

pr         


        
4条回答
  •  花落未央
    2021-02-19 03:33

    You need to make a minor change:

    class Foo(object):
    
        def get_bar(self):
            return "bar"
    
        bar = property(get_bar)
    
    print Foo().bar # prints bar
    

    The property needs to be an attribute of the class, not the instance; that's how the descriptor protocol works.

提交回复
热议问题