Default arguments in a child class and an inheritance (Python 3.10) - python

I want a child class to inherit from a parent class all methods and attributes with one small change - setting a default value for one argument in the child class shared with the parent class. How can I do it? With following code, I get an AttributeError when trying to call add method on the child class' instance.
https://pastebin.com/WFxmbyZD
def ParentClass():
"""An exemplary parent class."""
def __init__(self, a, b):
self.a = a
self.b = b
def adder(self):
return a + b
def ChildClass(ParentClass):
"""An exemplary child class."""
def __init__(self, a, b=3):
super().__init__(a, b)
child_class_instance = ChildClass(5)
print(child_class_instance.adder())

You have a mistake declaring the class.
I will show you examples here. The child class can have a different signature for the constructor and the methods.
class ParentClass:
"""An exemplary parent class."""
def __init__(self, a, b):
self.a = a
self.b = b
def adder(self):
return self.a + self.b
def adder_bis(self, c):
return self.a + self.b + c
class ChildClass(ParentClass):
"""An exemplary child class."""
def __init__(self, a, b=3):
super().__init__(a, b)
def adder_bis(self):
return super().adder_bis(self.a)
child_class_instance = ChildClass(5)
print(child_class_instance.adder())
print(child_class_instance.adder_bis())

I commented what I thought was wrong:
class ParentClass(): #class instead of def
"""An exemplary parent class."""
def __init__(self, a, b):
self.a = a
self.b = b
def adder(self):
return self.a + self.b #use self here
class ChildClass(ParentClass): #class instead of def
"""An exemplary child class."""
def __init__(self, a, b=3):
super().__init__(a, b)
child_class_instance = ChildClass(5)
print(child_class_instance.adder())
output:
8

Related

Python encapsulate data for a class

I have two python classes, A and B that inherits from A.
At runtime, I only have one instance of class A, but many instances of class B.
class A:
def __init__(self, a):
self.a = a
def _init2 (self, AA)
self.a = AA.a
class B(A):
def __init__(self, AA, b):
super()._init2(AA)
self.b = b
AA = A(0)
BB = B(AA, 1)
Is this the good way of writing it ? It seems ugly ...
It would probably be better to remove init2 and only use __init__. Having both is confusing and unnatural.
class A:
def __init__(self, obj):
# I believe that this is what you tried to achieve
if isinstance(obj, type(self)):
self.a = obj.a
else:
self.a = obj
class B(A):
def __init__(self, A, b):
super().__init__(A)
self.b = b
On a side note, there are too many things called A here. The A in def __init__(self, A, b): is most probably not referring to the A that you expect.

Accidentally calling an ovverriden method from base class's __init__

This program seems to do everything by the book, yet this issue cropped up: while a base class was being init'ed a member method was called that is overriden in the derived class and assumes that the derived class has been constructed.
Is there some best practice to protect against this?
#!/usr/bin/env python3
class A:
def __init__(self):
self.ax = 1
print(self)
def __repr__(self):
return "{} ax: {}".format(self.__class__.__name__, self.ax)
class B(A):
def __init__(self):
super().__init__()
self.bx = 10
def __repr__(self):
return super().__repr__() + " bx: {}".format(self.bx)
if __name__ == "__main__":
B()
And here's the error:
AttributeError: 'B' object has no attribute 'bx'
Generally, unless you really know what you are doing, you want to call the superclass initialization after everything your class needs to do is done. Same with this example, repr is trying to print self.bx before you initialize it. If you do
class B(A):
def __init__(self):
self.bx = 10
super().__init__()
def __repr__(self):
return super().__repr__() + " bx: {}".format(self.bx)
it works as expected
Edited:
Instead of doing computation on __init__, one idea may be to do that in a factory function/classmethod.
Example instead of doing:
class A:
def __init__(self, a, b):
self.a = a
self.b = b
self.initialize()
def initialize(self):
# do some things
Do:
class A:
def __init__(self, a, b):
self.a = a
self.b = b
#classmethod
def from_a_b(cls, a, b):
instance = cls(a, b)
instance.initialize()
return instance

Python inheritance: pass all arguments from base to super class

I am not quite used to class inheritance in Python yet. All I want to do is simply pass all arguments from my base class to the super class when it is created:
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
c = self.a + self.b
return B(c=c)
class B(A):
def __init__(self, c):
self.c = c
my_A = A(a=1, b=2)
my_B = my_A.do()
print(my_B.c)
This works as expected. However, what I want is to also be able to call the arguments a and b from the x2 instance of the class my_B, so that I can directly write my_B.a for instance. I know this is done with super() like this:
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
c = self.a + self.b
return B(a=self.a, b=self.b, c=c)
class B(A):
def __init__(self, a, b, c):
super(B, self).__init__(a=a, b=b)
self.c = c
my_A = A(a=1, b=2)
my_B = my_A.do()
print(my_B.a)
print(my_B.b)
However, I don't want to explicitly write all arguments of A when I create the instance of B. Is there a way to automatically pass all arguments from class A to class B?
Based on your comment, you could do something like this:
class B(A):
def __init__(self, c, an_a):
super(B, self).__init__(an_a.a, an_a.b)
self.c = c
You may instead prefer to keep your current constructor and add a from_a static method:
class B(A):
def __init__(self, c, a, b): # note order
super(B, self).__init__(a=a, b=b)
self.c = c
#staticmethod
def from_a(c, an_a):
return B(c, an_a.a, an_a.b)
Finally, if you don't want to type out all of those parameters, you can add an args() method to A and then use the collection unpacking function syntax:
class A:
...
def args(self):
return (self.a, self.b)
class B(A):
def __init__(self, c, *args): # Note *args
super(B, self).__init__(*args)
self.c = c
#staticmethod
def from_a(c, an_a):
return B(c, *an_a.args())
Now B's constructor takes the parameter special to B, followed by any number of parameters which just get passed to A's constructor. This allows you to do the tuple unpacking when calling the constructor, instead of listing everything out manually.
Ok, thanks for your comments. I have come up with this solution:
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def do(self):
c = self.a + self.b
return B(self, c)
class B:
def __init__(self, base, c):
self.base = base
self.c = c
my_A = A(a=1, b=2)
my_B = my_A.do()
print(my_B.base.a)
print(my_B.base.b)
print(my_B.c)
This removes the inheritance of class B and makes the code slightly less readable, but I guess it will do, right? 😊
yup there is a way use key word arguments so :
class A(object):
def __init__(self,**kwargs):
# Non pythonic and a bit of a hack
self.kwargs = kwargs
vars(self).update(kwargs)
def do(self):
c = self.a + self.b
return B(c=c, **kwargs)
class B(A):
def __init__(self, c, **kwargs):
self.c = c
super(B, self).__init__(**kwargs)
my_A = A(a=1, b=2)
my_B = my_A.do()
print(my_B.a)
print(my_B.b)
print(my_B.c)
This does what you are after nonethless the way in which it was written before was a bit more pythonic when run this should output:
1
2
3
The downside of doing this is that now A has not limit in terms of the number of attributes but you could ensure this with an assertion or something I guess.

Inheritance inside Classes Python3

I need something like this
class Parent(object):
class Base(object):
def __init__(self, a, b):
self.a = a
self.b = b
class Derived(Base):
def __init__(self, a, b, c):
super(Derived,self).__init__(a, b)
self.c = c
def doit():
pass
parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()
When I try to run this, i get this following error: NameError: name 'Derived' is not defined
I tried with 'Base' in the place of 'Derived' in super() - didn't help
Class inheritance does not change the parent class. In this case your Parent class only contains the original Base class and not the derived class.
You can simply use monkey-patching to solve this problem,
class Parent(object):
pass
class Base(object):
def __init__(self, a, b):
self.a = a
self.b = b
class Derived(Base):
def __init__(self, a, b, c):
super(Derived,self).__init__(a, b)
self.c = c
def doit(self):
pass
Parent.Derived = Derived
parent = Parent()
x, y , z = 1, 1, 1
derived = parent.Derived(x,y,z)
derived.doit()
Prefixing 'Derived' with 'Parent.', made it. As I already have commented on the question. This is just for experimenting with the 'Derived' class. But I am still wondering how the, 'class Derived(Base):' is fine (without 'Parent.' prefix for 'Base' class)
class Parent(object):
class Base(object):
def __init__(self, a, b):
self.a = a
self.b = b
class Derived(Base):
def __init__(self, a, b, c):
super(Parent.Derived,self).__init__(a, b)
self.c = c
def doit():
pass
parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()

Elegant multiple inheritance in Python

I'm currently using this pattern to create a class C that inherits from A and B. I couldn't call super().__init__ from C since I would have to do the same in A and B, and the unexpected parameter would cause problems at the top level. I feel like this isn't very elegant. What is the proper way to do multiple inheritance in Python? I guess it is unusual to query the mro to find out if the superclass expects a parameter?
class A:
def __init__(self, something):
self.a = X(something)
def method_a(self):
self.a.go()
def method_ab(self):
self.a.go2()
class B:
def __init__(self, something):
self.b = X(something)
def method_b(self):
self.b.go()
def method_ab(self):
self.b.go2()
class C(A, B):
def __init__(self, something):
self.a_ = A(something)
self.b_ = B(something)
#property
def a(self):
return self.a_.a
#property
def b(self):
return self.b_.b
def method_ab(self):
for x in [self.a, self.b]:
x.method_ab()
The best solution I found was to use a base class to absorb the extra parameters:
class Base:
def __init__(self, something):
pass
def method_ab(self):
pass
class A(Base):
def __init__(self, something):
super().__init__(something)
self.a = X(something)
def method_a(self):
self.a.go()
def method_ab(self):
super().method_ab()
self.a.go()
class B(Base):
def __init__(self, something):
super().__init__(something)
self.b = X(something)
def method_b(self):
self.b.go()
def method_ab(self):
super().method_ab()
self.b.go()
class C(A, B):
pass

Categories

Resources