Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python property returning property object

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've seen How do Python properties work?, How to set a python property in __init__, but they all use the decorator method, which i don't because i want a different name. And I need access to self

How do i get the property to behave?

like image 815
gcq Avatar asked Feb 16 '14 13:02

gcq


People also ask

How do you return a property in Python?

Return value from property()property() returns the property attribute from the given getter, setter, and deleter. If no arguments are given, property() returns a base property attribute that doesn't contain any getter, setter or deleter. If doc isn't provided, property() takes the docstring of the getter function.

What is property object in Python?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.

How do you access the properties of an object in Python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

How do you remove a property of an object in Python?

You can delete the object property by using the 'del' keyword.


1 Answers

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.

like image 199
jonrsharpe Avatar answered Sep 19 '22 14:09

jonrsharpe