相关疑难解决方法(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万
查看次数

是什么让用户定义的对象不在Python中抛出AttributeError?

可能重复:
为什么我不能直接向任何python对象添加属性?
为什么不能在python中向对象添加属性?

以下代码不会抛出AttributeError

class MyClass():
    def __init__(self):
        self.a = 'A'
        self.b = 'B'
my_obj = MyClass()
my_obj.c = 'C'
Run Code Online (Sandbox Code Playgroud)

这与之形成鲜明对比

>>> {}.a = 'A'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'a'
Run Code Online (Sandbox Code Playgroud)

有什么区别?它是关于dict是一个内置类,而MyClass是用户定义的吗?

python oop

5
推荐指数
1
解决办法
223
查看次数

为什么我不能将任意成员添加到对象实例?

我才意识到:

class A(object): pass

a = A()
a.x = 'whatever'
Run Code Online (Sandbox Code Playgroud)

Works(不会引发错误并创建新x成员).

但是这个:

a = object()
a.x = 'whatever'
Run Code Online (Sandbox Code Playgroud)

举:

AttributeError: 'object' object has no attribute 'x'
Run Code Online (Sandbox Code Playgroud)

虽然我可能永远不会在实际生产代码中使用它,但我对于不同行为的原因有点好奇.

任何提示?

python

5
推荐指数
1
解决办法
101
查看次数

标签 统计

python ×4

attributes ×2

instances ×1

language-design ×1

oop ×1