[英]OOP attribute definition
I want to define an attribute in a method: 我想在方法中定义一个属性:
class variables:
def definition(self):
self.word = "apple"
Then I want to use the defined attribute: 然后,我想使用定义的属性:
test = variables()
print test.definition.word
Instead of writing 'apple'
I get an error: 我没有写
'apple'
而是得到一个错误:
Traceback (most recent call last):
File "bezejmenný.py", line 6, in <module>
print test.definition.word
AttributeError: 'function' object has no attribute 'word'
definition
is a method so you need to execute it definition
是一种方法,因此您需要执行它 Because you are assigning a variable to self, you can access it through your instance as follows 因为您要为自己分配一个变量,所以可以通过实例通过以下方式访问它
test = variables() test.definition() print test.word
A few ideas: 一些想法:
definition
method definition
方法 Extend your class with object
because everything in python is objects (python 2.x only) 扩展你的类
object
,因为一切都在巨蟒对象(Python的2.X只)
class Variables(object): def __init__(self): self.word = 'I am a word' variables = Variables() print variables.word
You can access instance attribute like this: 您可以像这样访问实例属性:
test = variable()
test.definition()
print test.word
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.