Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从类外部添加属性?_Python_Oop - Fatal编程技术网

Python 如何从类外部添加属性?

Python 如何从类外部添加属性?,python,oop,Python,Oop,我知道这是基本的,但从类外部向类对象添加属性的最佳方法是什么?这是通过使用点操作符来完成的。有关更多信息,请参阅 class Thing(object): def __init__(self): pass x = Thing() x.attribute = "my attribute" >>> print (x.attribute) 'my attribute' 最好的办法是不要这样做。第二个最好的方法是cls.new\u attribute=v

我知道这是基本的,但从类外部向类对象添加属性的最佳方法是什么?

这是通过使用点操作符来完成的。有关更多信息,请参阅

class Thing(object):
    def __init__(self):
        pass

x = Thing()

x.attribute = "my attribute"

>>> print (x.attribute)
'my attribute'

最好的办法是不要这样做。第二个最好的方法是
cls.new\u attribute=value
。注意,他说的是类对象,而不是类实例对象。所以你的例子是错误的。正确的代码应该是
Thing.attribute=“my attribute”
。考虑到op的假定技能水平,我认为这种错误在这种情况下并不重要,但仍然是一个好问题。