user1595929
user1595929

Reputation: 1372

inheriting from list and other object

I have a class A defining basics behaviour of my object and a class B inheriting from list and C inheriting from 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)

What I'd like is that the user build object B or C which behaves like a list or a str, those classes just have metadata usefull for our application but not for the user ... using class B is easy, if I want to change the values, I can clear it or append new values ... but how can I modify the value of a C object. I checked setattr but this one required an attribute name ...

thanks, Jerome

Upvotes: 0

Views: 68

Answers (2)

Marcin
Marcin

Reputation: 49826

This works:

>>> 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
>>> 

You can change the metadata on a C instance. Like str, you can't change the value of the characters it contains.

If you want a mutable string, you're going to have to create that in pure python. However, given that everyone else gets by without that, consider whether you can use the built in facilities, such as TextStream.

Upvotes: 1

Tom Dalton
Tom Dalton

Reputation: 6190

You can't. Strings are immutable - you cannot change their value once created. Lists are mutable, which is why you can change their value (contents) after creation.

Upvotes: 0

Related Questions