python - 什么时候可以动态地向对象添加字段?

标签 python python-3.x curses

我正在用 python 学习 curses,想给 curses 窗口对象添加一个属性。

我的最小程序是:

import curses
try:
  stdscr = curses.initscr()
  stdscr.cur_line = 0
finally: 
  #clean-up so your terminal isn't wrecked by above error
  curses.nocbreak()
  stdscr.keypad(False)
  curses.echo()
  curses.endwin()

错误是:

$ python3 tmp
Traceback (most recent call last):
  File "tmp", line 4, in <module>
    stdscr.cur_line = 0
AttributeError: '_curses.curses window' object has no attribute 'cur_line'

但是,这是可行的:

class Temp:
    def __init__(self):
        pass
t = Temp()
t.cur_line = 0 #does not fail

我的问题是:动态添加字段到实例什么时候会失败? python 如何区分用户定义类的实例和 curses 库中的类实例?

最佳答案

大多数情况下,发生这种情况是因为您试图将属性添加到用 C 编写的库,而不是纯 python 对象。

>>> import pickle, cPickle
>>> pickle.dump.a=1
>>> cPickle.dump.a=1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'a'

关于python - 什么时候可以动态地向对象添加字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23499588/

相关文章:

python - 在 Spyder IDE 上运行 Pyinstaller(或 Anaconda3 提示符)

c++ - Valgrind 在使用适当的 free() 和 end() 后显示 ncurses 命令的内存泄漏

python - 如何使用 Python 中的 API 重命名 Google Sheets 电子表格中的(工作)表?

用于处理 unicode 字符串的 Python 2.7/3 C 模块

python - python多处理队列中的死锁

当我向 keyname() 发送大于 256 的 int 计数器变量时,Curses keyname() 会出现段错误

c - 如何在c程序中使用dialog.h

python - Pandas Groupby : How to get the first string

python - 如何在全局变量上使用 __get__() ?

python-3.x - tensorflow tensorflow.contrib.learn.Estimator 加载训练模型