继承自列表和其他对象

时间:2014-08-06 15:55:27

标签: python

我有一个A类定义了我的对象的基本行为,B类继承自list和C继承自str

class A(object):
  def __init__(self, a):
    self.a = a

class B(list, A):
  def __init__(self, inputs, a):
    A.__init__(self, a)
    return list.__init__(self, [inputs])

class C(str, A):
  def __new__(self, input, a):
    return str.__new__(self, input)
  def __init__(self, inputs, a):
    A.__init__(self, a)

def __init__(self, input, a):
    A.__init__(self, a)

我想要的是用户构建对象B或C,其行为类似于列表或str,这些类只有对我们的应用程序有用的元数据而不是用户...使用类B很容易,如果我想更改值,我可以清除它或附加新值...但我怎样才能修改C对象的值。我检查了 setattr ,但这个需要一个属性名称......

感谢, 杰罗姆

2 个答案:

答案 0 :(得分:1)

这有效:

>>> class A(object):
...   def __init__(self, a):
...     self.a = a
... 
>>> class B(list, A):
...   def __init__(self, inputs, a):
...     A.__init__(self, a)
...     return list.__init__(self, [inputs])
... 
>>> class C(str, A):
...   def __new__(self, input, a):
...     return str.__new__(self, input)
...   def __init__(self, inputs, a):
...     A.__init__(self, a)
... 
>>> c = C('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 3 arguments (2 given)
>>> c = C('foo', 1)
>>> c
'foo'
>>> c.a
1
>>> c.a = 2
>>> c.a
2
>>> 

您可以更改C实例上的元数据。与str一样,您无法更改其中包含的字符的值。

如果你想要一个可变的字符串,你将不得不在纯python中创建它。但是,考虑到其他所有人都没有,请考虑是否可以使用内置工具,例如TextStream

答案 1 :(得分:0)

你不能。字符串是不可变的 - 一旦创建,您就无法更改它们的值。列表是可变的,这就是为什么你可以在创建后更改它们的值(内容)。

相关问题