Python property returning property object

后端 未结 4 1826
别跟我提以往
别跟我提以往 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:42

    You can do it like this

    class Foo(object):
        def __init__(self):
            self.__bar = None
    
        def get_bar(self):
            return self.__bar
    
        def set_bar(self, value):
            self.__bar = value
    
        bar = property(get_bar, set_bar)
    
    foo = Foo()
    print foo.bar    # None
    foo.bar = 1
    print foo.bar    # 1
    

提交回复
热议问题