Onilol Onilol - 7 months ago 24
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:
an instance, I get the following:

(property object at 0x0000000004FDCBD8,)

What am I doing wrong here?

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

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

Jim Jim

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()
'Humpty Dumpty'

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