Python property returning property object

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

    The object is not instantiated.

    class Foo(object):
      def get_bar(self):
        return "bar"
    
    bar = Foo()
    print(bar.get_bar)
    
    0 讨论(0)
  • 2021-02-19 03:32

    You can also do it like shown here:

    class Foo(object):
        def __init__(self):
            self._bar = None
    
        @property
        def bar(self):
            return self._bar
    
        @bar.setter
        def bar(self, value):
            self._bar = value
    
        @bar.deleter
        def bar(self):
            self._bar = None # for instance
    

    which is equivalent to:

    class Also_Foo(object):
        def __init__(self):
            self._bar = None
    
        def get_bar(self):
            return self._bar
    
        def set_bar(self, value):
            self._bar = value
    
        def del_bar(self):
            self._bar = None # for instance
    
        bar = property(fget=get_bar, fset=set_bar, fdel=del_bar, doc=None)
    

    BUT without polluting the class namespace with get and set methods for each attribute.

    You retain external direct access to the variable by using ._bar instead of .bar.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题