我在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
我的问题是:何时向实例动态添加字段失败?如何在我的用户定义的类的实例和curses库中的类的实例之间识别python?
答案 0 :(得分:1)
大多数情况下,这是因为您尝试将属性添加到用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'