python - OOP 属性定义

标签 python python-2.7 oop

我想在方法中定义一个属性:

class variables:
    def definition(self):
        self.word = "apple"

然后我想使用定义的属性:

test = variables()
print test.definition.word

我没有写'apple',而是收到一个错误:

Traceback (most recent call last):
  File "bezejmenný.py", line 6, in <module>
    print test.definition.word
AttributeError: 'function' object has no attribute 'word'

最佳答案

  1. definition 是一个方法所以你需要执行它
  2. 因为您正在为自己分配一个变量,所以您可以通过您的实例访问它,如下所示

    test = variables()
    test.definition()
    print test.word
    

一些想法:

  • 最佳做法是类名以大写字母开头
  • 如果你只是想让你的类有一个字段,你不需要你的定义方法
  • object 扩展你的类,因为 python 中的一切 都是对象(仅限 python 2.x)

    class Variables(object):
        def __init__(self):
            self.word = 'I am a word'
    
    variables = Variables()
    print variables.word
    

关于python - OOP 属性定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33501611/

相关文章:

python - 我可以在安装 Canopy 的同时安装 Anaconda 吗?

python - 搜索Python对象层次结构

python - Python中数组的移动平均值

java - 为什么对象的声明类型在运行时很重要?

algorithm - 如何适应需要成为应用程序一部分的新逻辑

python - 为什么cherrypy服务器会记录错误消息,即使它看起来可以工作?

python在一个循环中产生和停止迭代?

python - 如何将 python 2.7 功能设置为 Python 2.6?

python - 如何将字典列表转换为以组合元组为键的多个字典?

php - 有没有一种简单的方法可以在 php 5.3 中模拟友谊