相关疑难解决方法(0)

无法设置对象类的属性

所以,我在回答这个问题时正在玩Python ,我发现这是无效的:

o = object()
o.attr = 'hello'
Run Code Online (Sandbox Code Playgroud)

由于AttributeError: 'object' object has no attribute 'attr'.但是,对于从object继承的任何类,它是有效的:

class Sub(object):
    pass

s = Sub()
s.attr = 'hello'
Run Code Online (Sandbox Code Playgroud)

打印s.attr按预期显示"你好".为什么会这样?Python语言规范中的内容指定您不能将属性分配给vanilla对象?

python attributes language-design

81
推荐指数
2
解决办法
1万
查看次数

为什么不能在python中向对象添加属性?

(用Python shell编写)

>>> o = object()
>>> o.test = 1

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
    pass

>>> t = test1()
>>> t.test

Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
    pass

>>> t = test2()
>>> t.test = 1
>>> …
Run Code Online (Sandbox Code Playgroud)

python attributes instances

62
推荐指数
2
解决办法
3万
查看次数

标签 统计

attributes ×2

python ×2

instances ×1

language-design ×1