4

Consider the following piece of code:

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ABCD(ABC):
    def __init__(self, abc, d):
        # How to initialize the base class with abc in here?
        self.d = d

abc = ABC(1, 2, 3)
abcd = ABCD(abc, 4)
print(abcd.a)

What is a Pythonic way of initializing the base class with abc? If I used

super().__init__(abc.a, abc.b, abc.c)

I would have to change ABCD everytime I add someting to ABC. What I could do is to use

self.__dict__.update(abc.__dict__)

However, this feels clumsy and will break when ABC uses a different underlying implementation than dict (e.g. __slots__). Are there some alternative ways?

3
  • If you put the arguments specific to ABCD at the beginning, you could do: __init__ (self, d, *args, **kargs) and then super().__init__(*args, **kargs). Commented May 10, 2014 at 11:23
  • @Holt: Then I would need to use abcd = ABCD(4, abc.a, abc.b, abc.c) instead of abcd = ABCD(4, abc), thus forcing the user of ABCD to unpack abc manually. Commented May 10, 2014 at 11:27
  • Sorry, I didn't read the end of your code, I though you wanted to do ABCD(4, 1, 2, 3) directly. Commented May 10, 2014 at 11:30

1 Answer 1

1

If you pass an object of type abc to the constructor, maybe you should have abc as field and not inheritance.

e.g. maybe:

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ABCD:
    def __init__(self, abc, d):
        # How to initialize the base class with abc in here?
        self.abc = abc

abc = ABC(1, 2, 3)
abcd = ABCD(abc, 4)
print(abcd.abc.a)

Per your comment, I would write method to copy the ABC part. This way this method would be "responsibility" of ABC.

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def copy_init(other):
        self.a = other.a
        self.b = other.b
        self.c = other.c

class ABCD(ABC):
    def __init__(self, abc, d):
        self.copy_init(abc)
        self.d = d
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this is often the case. However, in my particular case, I need ABCD to inherit from ABC so it behaves like a subclass of ABC and the users can access all of ABC's attributes directly.
In that case, I would write a method (of ABC) to do this copying. See EDIT above
@eran Copying ABC is not very practical if you are inheriting a giant class from an external library. It's hard to ensure all things get copies in the correct way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.