Jon Warneke
Jon Warneke

Reputation: 337

Subclass that adds

First, I have a class:

class MyClass(object):
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

class AnotherClass:
    # what goes here ???

What I'd like to do is make AnotherClass take two inputs,

  1. an instance (call it a) of MyClass
  2. another argument, arg2,

so that arg2 can be used to make additional attributes for AnotherClass, and every attribute of MyClass is also an attribute of the AnotherClass, which is not found anew or copied into the AnotherClass instance, but found by looking at a. (Assume that MyClass has lots of attributes, unlike the example shown.) For example, I'd like to be able to do

>>> a = MyClass(1, 2)
>>> b = AnotherClass(a, 3)
>>> b.attr1 # found via a.attr1
1
>>> b.attr2 # found via a.attr1
2
>>> b.attr3
3
>>> c = AnotherClass(a, 4)
>>> c.attr1 # found via a.attr1
1
>>> c.attr2 # found via a.attr1
2
>>> c.attr3
4

What code should be found in AnotherClass?

Upvotes: 0

Views: 39

Answers (2)

sowrd299
sowrd299

Reputation: 149

If you really want to do what you want to do, the constructor you want is:

def __init__(self, a, arg1):
    self.__dict__ = dict(a.__dict__)
    self.attr3 = arg1

The second line effectively takes every attribute currently assigned to a, and then assigns copies of them to self (__dict__ being the dictionary in which python stores an objects attributes).

Upvotes: 1

sowrd299
sowrd299

Reputation: 149

The code you want is:

def __init__(self, a : Class, arg2):
    super().__init__(a.attr1,a.attr2)
    self.attr3 = arg2

However, unless your code specifically wants instances of SubClasses to initialize as pseudo-clones of pre-existing instance of Class, you may find this code more useful:

def __init__(self, attr1, attr2, arg2):
    super().__init__(attr1,attr2)
    self.attr3 = arg2

Upvotes: 0

Related Questions