Onilol Onilol - 4 months ago 9
Python Question

Assign model method's return value to model attribute

I have a class similar to this:

class X(models.Model):
def hello(self):
return "Humpty Dumpty"

name = (hello,)
age = models.IntegerField()


now when I run in the console:
y.name
being
y
an instance, I get the following:


(property object at 0x0000000004FDCBD8,)


What am I doing wrong here?

I tried using the
@property
above the method but it didn't work.

I'd like to get "Humpty Dumpty" when I access
y.name
. So the method would assign it's value to the attribute.

Jim Jim
Answer

If you just want to get the function called on attribute access, define name as property and provide your function foo to it:

name = property(hello)

This will set the fget inside the property to your function hello.

y = X()
y.name
'Humpty Dumpty'

Take note, there's a pretty good tutorial on descriptors in the Python Official docs.