Python property property property

I have a class like this:

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

    def get_bar(self):
        return "bar"

print Foo().bar  #this prints <property object at 0x0051CB40>

I saw How Python properties work? , How to install python property in the __init__ , but they all use a decorator method that I do not, because I want a different name. And I need access toself

How to make a property behave?

+6
source share
4 answers

You need to make minor changes:

class Foo(object):

    def get_bar(self):
        return "bar"

    bar = property(get_bar)

print Foo().bar # prints bar

A property must be an attribute of a class, not an instance; this is how the descriptor protocol works .

+7
source

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
+5
source

, :

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

:

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 methods getand setfor each attribute.

You keep external direct access to the variable by using ._barinstead .bar.

+2
source

Object not created.

class Foo(object):
  def get_bar(self):
    return "bar"

bar = Foo()
print(bar.get_bar)
-1
source

Source: https://habr.com/ru/post/1527185/


All Articles