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?
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.
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.
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.
You can delete the object property by using the 'del' keyword.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With