所以,我在回答这个问题时正在玩Python ,我发现这是无效的:
o = object()
o.attr = 'hello'
由于AttributeError: 'object' object has no attribute 'attr'.但是,对于从object继承的任何类,它是有效的:
class Sub(object):
    pass
s = Sub()
s.attr = 'hello'
打印s.attr按预期显示"你好".为什么会这样?Python语言规范中的内容指定您不能将属性分配给vanilla对象?
我正在尝试使用新式属性声明:
class C(object):
    def __init__(self):
        self._x = 0
    @property
    def x(self):
        print 'getting'
        return self._x
    @x.setter
    def set_x(self, value):
        print 'setting'
        self._x = value
if __name__ == '__main__':
    c = C()
    print c.x
    c.x = 10
    print c.x
并在控制台中查看以下内容:
pydev debugger: starting
getting
0
File "\test.py", line 55, in <module>
c.x = 10
AttributeError: can't set attribute
我究竟做错了什么?PS:旧式宣言工作正常.
这是我的代码
N = namedtuple("N", ['ind', 'set', 'v'])
def solve()
    items=[]
    stack=[]
    R = set(range(0,8))
    for i in range(0,8):
        items.append(N(i,R,8))      
        stack.append(N(0,R-set(range(0,1)),i))
    while(len(stack)>0): 
        node = stack.pop()
        print node
        print items[node.ind]   
        items[node.ind].v = node.v
在最后一行,我不能将items[node.ind].v值设置node.v为我想要的,并得到错误
"AttributeError: can't set attribute"
我不知道什么是错的,但它必须是基于语法的东西,因为使用语句node.v+=1也会显示相同的错误.我是Python的新手,所以请建议一种方法来实现上述变更.
我想我还没有考虑如何定义一个从namedtuple子类化的类:
from collections import namedtuple
PD = namedtuple('PD', 'x y z')
p1 = PD(0, 'u', 1)
print p1.x #<== this works
class PDsub(PD):
   __slots__ = ()
   def __new__(cls, x, y, z):
        self = super(PDsub, cls).__new__(cls, x, y, z)
        return self
   def __init__(self, a):
        self.x, self.y, self.z = a, a, a
   def __str__(self):
        return 'Foo'
p2 = PDsub(5) #<== this does not work
这段代码提出来了TypeError : __new__() takes exactly 4 arguments (2 given).
有什么想法吗?