相关疑难解决方法(0)

为什么不能在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对象添加属性?

我有这个代码:

>>> class G:
...   def __init__(self):
...     self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
Run Code Online (Sandbox Code Playgroud)

这段代码:

>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
Run Code Online (Sandbox Code Playgroud)

根据我的Python知识,我会说datetime覆盖setattr/ getattr,但我不确定.你能在这里说清楚吗?

编辑:我不是特别感兴趣datetime.我总是想知道对象.

python attributes object

21
推荐指数
2
解决办法
8749
查看次数

Python语言问题:object()与Function的属性

在python中,为这样的对象实例创建新属性是非法的

>>> a = object()
>>> a.hhh = 1
Run Code Online (Sandbox Code Playgroud)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hhh'
Run Code Online (Sandbox Code Playgroud)

但是,对于一个函数对象,它是可以的.

>>> def f():
...   return 1
...
>>> f.hhh = 1
Run Code Online (Sandbox Code Playgroud)

这种差异背后的理由是什么?

python function object

17
推荐指数
2
解决办法
1322
查看次数

标签 统计

python ×3

attributes ×2

object ×2

function ×1

instances ×1