python 缺少对象成员变量

python object member variable missing

我有一个构造函数,它创建一个子对象的成员对象class:

class OpenSprinkler:
  class CV:
    my_args = ['rsn', 'rbt', 'en', 'rd', 're']
    my_longhand = {'reset_all':'rsn',
                   'reboot':'rbt',
                   'enable':'en',
                   'rain_delay':'rd',
                   'remote_extension':'re'}

    def __init__(self, p):
      print('set parent of %r\n' % (self,))
      self.parent = p
      print('parent set to %r\n' % (p,))
      self.my_args.extend(self.my_longhand.keys())

  def __init__(self, hostname, password, log=None):
    self.cv = self.CV(self)

输出确认调用了成员的构造函数:

>>> c = openSprinkler.OpenSprinkler('foo','bar')
set parent of <openSprinkler.OpenSprinkler.CV object at 0xb6a58df0>

parent set to <openSprinkler.OpenSprinkler object at 0xb6a58dd0>

>>> repr(c.cv)
'<openSprinkler.OpenSprinkler.CV object at 0xb6a58df0>'

但是当我查看成员时,cv.parent 似乎不存在:

>>> dir(c.cv)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'my_args', 'my_longhand']

cv.my_args 包含扩展列表。知道这里发生了什么吗?

更新: 正如 Alec 指出的那样,代码示例确实有效。 示例中省略了实际问题,我选择了覆盖 setattr 方法而不允许设置父级。

原来:

def __setattr__(self, name, value):
  if name in self.my_args:
    if name in self.my_longhand.keys():
      name = self.my_longhand[name]
    self.parent._json_get('cv', {name:value})

现在:

def __setattr__(self, name, value):
  if name in self.my_args:
    if name in self.my_longhand.keys():
      name = self.my_longhand[name]
    self.parent._json_get('cv', {name:value})
  else:
    super().__setattr__(name, value)

是否有可能您在被调用代码的其他地方有一个 openSprinkler 对象?直接实例化OpenSprinkler好像包含了你的方法:

c = OpenSprinkler('foo','bar')

print(dir(c.cv))
# ['__class__', '__delattr__', '__dict__', '__dir__', 
# '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
# '__gt__', '__hash__', '__init__', '__le__', '__lt__', 
# '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
# '__repr__', '__setattr__', '__sizeof__', '__str__', 
# '__subclasshook__', '__weakref__', 'my_args', 'my_longhand', 'parent']