简体   繁体   English

将模型方法的返回值分配给模型属性

[英]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: 现在,当我在控制台中运行时: y.namey的实例,我得到以下信息:

(property object at 0x0000000004FDCBD8,) (属性对象位于0x0000000004FDCBD8,)

What am I doing wrong here? 我在这里做错了什么?

I tried using the @property above the method but it didn't work. 我尝试使用上述方法中的@property ,但没有用。

I'd like to get "Humpty Dumpty" when I access y.name . 访问y.name时,我想获得“ Humpty Dumpty”。 So the method would assign it's value to the attribute. 因此,该方法会将其值分配给属性。

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并为其提供函数foo

name = property(hello)

This will set the fget inside the property to your function hello . 这会将属性内的fget设置为函数hello

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

Take note, there's a pretty good tutorial on descriptors in the Python Official docs. 请注意,Python Official文档中有一个关于描述符的很好的教程

That's invalid syntax. 那是无效的语法。 You need to do something like this: 您需要执行以下操作:

class X:
  def __init__(self):
      self.name = self.hello()

  def hello(self):
    return "Humpty Dumpty"

test = X()
print(test.name) # prints "Humpty Dumpty"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM