Python inheritance changing child class field - python

I am creating a database in a for of classes with inheritance. I would like Child class to inherit all field of parent class, however it doesn't happen as I am getting "AttributeError: 'Child' object has no attribute 'default'". If I define 'default' variable in Child class, I will get it working, but I want that Child inherited parent value for 'default' and not redefine it again at Child class. If I don't specify __init__ method in Child class, all fields are inherited, but I can't change their value.
#!/usr/bin/env python3
import sys
class Parent():
def __init__(self, y, x):
self.result = self.action(x,y)
default = 5
def action(self,x,y):
return (x*y)
def setResult(self, x):
def __init__(self, y, x):
self.result = x
class Child(Parent):
def __init__(self, y, x):
self.result = self.action(x,y)
def action(self,x,y):
return (x/y)
def main(argv):
data = Child(2,3)
print (data.result)
print (data.default)
if __name__ == "__main__":
main(sys.argv[1:])

To consolidate the comments you received into an actual answer:
class Parent():
def __init__(self, y, x):
self.result = self.action(x,y)
self.default = 5 #----- this requires a "self" to attach to any instance of the class
class Child(Parent):
def __init__(self, y, x):
super().__init__(y, x)
self.result = self.action(x,y)
To restate everything that has been stated in the comments:
You are overriding __init__ by making a function for it.
__int__ is a built-in function, if you don't make one yourself - python uses one it makes itself. __init__ is always run when a class is being initiated.
When you declare variables to self in this function, you are adding the variables to any instance of the class that is created. (as opposed to using self in some other function)
By writing your own version of __init__ you are taking on the burden of making sure that it creates every value the class is supposed to have - for cases where you want to make use of inheritance, this is why we have the super() function.
The super() function is used to give access to methods and properties of a parent or sibling class.
By calling super().__init__(y, x) you call Parent()'s __init__ function and thus 'inherit' its values / settings / properties.
Just to crystallize the subject more - the following two classes are (effectively) identical:
class Child(Parent):
def __init__(self, y, x):
super().__init__(y, x)
def action(self,x,y):
return (x/y)
class Child(Parent):
def action(self,x,y):
return (x/y)
Further reference:
https://www.w3schools.com/python/gloss_python_class_init.asp
https://www.w3schools.com/python/ref_func_super.asp

Related

reference instance attribute in child class

I am trying to call an instance variable from a "parent" class (subclass) to it's "child" class (subsubclass)
class mainclass():
def __init__(self):
self.mainclassvar1 = "mainclass"
class subclass(mainclass):
def __init__(self):
self.subclassvar1 = "subclass"
def changeval(self):
self.subclassvar1 = "subclassedited"
class subsubclass(subclass):
def __init__(self):
self.subsubclassvar1 = subclass.subclassvar1 #<- naturally this fails
def handler():
main=mainclass()
sub = subclass()
sub.changeval()
subsub = subsubclass()
print(subsub.subsubclassvar1)# <- how do I achieve this? I would expect "subclassedited" but it doesn't
if __name__ == "__main__":
handler()
The above does not work obviously but I am trying to show what I am trying to achieve in my head.
if I change the class subsubclass(subclass) as follows it semi-works:
class subsubclass(subclass):
def __init__(self):
subclass.__init__(self)
self.subsubclassvar1 = self.subclassvar1
however the returned value is the original default value of subclass instead of the expected subclassedited.
I am not sure if I should even be trying to do this but I've got some code where the logic has now come to this point and I want to try see if I can get details from the middle class in to the final child class in their final modified states instead of the defaults and without refactoring a lot of code.
Each __init__ method should be invoking the parent's __init__ method, so that the instance is properly initialized for all the classes in the hierarchy.
class mainclass:
def __init__(self):
super().__init__()
self.mainclassvar1 = "mainclass"
class subclass(mainclass):
def __init__(self):
super().__init__()
self.subclassvar1 = "subclass"
def changeval(self):
self.subclassvar1 = "subclassedited"
class subsubclass(subclass):
def __init__(self):
super().__init__()
# Not sure why you would really need this, but...
self.subsubclassvar1 = self.subclassvar1
There's no reason, though that subsub.subclassvar1 should be related to sub.subclassvar1, though. Calling sub.changeval() has nothing to do with subsub.

Correct way of returning new class object (which could also be extended)

I am trying to find a good way for returning a (new) class object in class method that can be extended as well.
I have a class (classA) which has among other methods, a method that returns a new classA object after some processing
class classA:
def __init__(): ...
def methodX(self, **kwargs):
process data
return classA(new params)
Now, I am extending this class to another classB. I need methodX to do the same, but return classB this time, instead of classA
class classB(classA):
def __init__(self, params):
super().__init__(params)
self.newParams = XYZ
def methodX(self, **kwargs):
???
This may be something trivial but I simply cannot figure it out. In the end I dont want to rewrite the methodX each time the class gets extended.
Thank you for your time.
Use the __class__ attribute like this:
class A:
def __init__(self, **kwargs):
self.kwargs = kwargs
def methodX(self, **kwargs):
#do stuff with kwargs
return self.__class__(**kwargs)
def __repr__(self):
return f'{self.__class__}({self.kwargs})'
class B(A):
pass
a = A(foo='bar')
ax = a.methodX(gee='whiz')
b = B(yee='haw')
bx = b.methodX(cool='beans')
print(a)
print(ax)
print(b)
print(bx)
class classA:
def __init__(self, x):
self.x = x
def createNew(self, y):
t = type(self)
return t(y)
class classB(classA):
def __init__(self, params):
super().__init__(params)
a = classA(1)
newA = a.createNew(2)
b = classB(1)
newB = b.createNew(2)
print(type(newB))
# <class '__main__.classB'>
I want to propose what I think is the cleanest approach, albeit similar to existing answers. The problem feels like a good fit for a class method:
class A:
#classmethod
def method_x(cls, **kwargs):
return cls(<init params>)
Using the #classmethod decorator ensures that the first input (traditionally named cls) will refer to the Class to which the method belongs, rather than the instance.
(usually we call the first method input self and this refers to the instance to which the method belongs)
Because cls refers to A, rather than an instance of A, we can call cls() as we would call A().
However, in a class that inherits from A, cls will instead refer to the child class, as required:
class A:
def __init__(self, x):
self.x = x
#classmethod
def make_new(cls, **kwargs):
y = kwargs["y"]
return cls(y) # returns A(y) here
class B(A):
def __init__(self, x):
super().__init__(x)
self.z = 3 * x
inst = B(1).make_new(y=7)
print(inst.x, inst.z)
And now you can expect that print statement to produce 7 21.
That inst.z exists should confirm for you that the make_new call (which was only defined on A and inherited unaltered by B) has indeed made an instance of B.
However, there's something I must point out. Inheriting the unaltered make_new method only works because the __init__ method on B has the same call signature as the method on A. If this weren't the case then the call to cls might have had to be altered.
This can be circumvented by allowing **kwargs on the __init__ method and passing generic **kwargs into cls() in the parent class:
class A:
def __init__(self, **kwargs):
self.x = kwargs["x"]
#classmethod
def make_new(cls, **kwargs):
return cls(**kwargs)
class B(A):
def __init__(self, x, w):
super().__init__(x=x)
self.w = w
inst = B(1,2).make_new(x="spam", w="spam")
print(inst.x, inst.w)
Here we were able to give B a different (more restrictive!) signature.
This illustrates a general principle, which is that parent classes will typically be more abstract/less specific than their children.
It follows that, if you want two classes that substantially share behaviour but which do quite specific different things, it will be better to create three classes: one rather abstract one that defines the behaviour-in-common, and two children that give you the specific behaviours you want.

I want to call parent class method which is overridden in child class through child class object in Python

class abc():
def xyz(self):
print("Class abc")
class foo(abc):
def xyz(self):
print("class foo")
x = foo()
I want to call xyz() of the parent class, something like;
x.super().xyz()
With single inheritance like this it's easiest in my opinion to call the method through the class, and pass self explicitly:
abc.xyz(x)
Using super to be more generic this would become (though I cannot think of a good use case):
super(type(x), x).xyz()
Which returns a super object that can be thought of as the parent class but with the child as self.
If you want something exactly like your syntax, just provide a super method for your class (your abc class, so everyone inheriting will have it):
def super(self):
return super(type(self), self)
and now x.super().xyz() will work. It will break though if you make a class inheriting from foo, since you will only be able to go one level up (i.e. back to foo).
There is no "through the object" way I know of to access hidden methods.
Just for kicks, here is a more robust version allowing chaining super calls using a dedicated class keeping tracks of super calls:
class Super:
def __init__(self, obj, counter=0):
self.obj = obj
self.counter = counter
def super(self):
return Super(self.obj, self.counter+1)
def __getattr__(self, att):
return getattr(super(type(self.obj).mro()[self.counter], self.obj), att)
class abc():
def xyz(self):
print("Class abc", type(self))
def super(self):
return Super(self)
class foo(abc):
def xyz(self):
print("class foo")
class buzz(foo):
def xyz(self):
print("class buzz")
buzz().super().xyz()
buzz().super().super().xyz()
results in
class foo
Class abc

Python base class' implicit super() call

Currently I am starting to revise my python's OOP knowledge. I stumbled upon super() definition, which suggests, that it provides a derived class with a set of instance variables and methods from a base class.
So I have this piece of code:
class foo:
bar = 5
def __init__(self, a):
self.x = a
def spam(self):
print(self.x)
class baz(foo):
pass
b = baz(5)
b.spam()
And this executed with no super() calls, no errors, and printed out 5.
Now when I add an __init__ method to the derived class, like this:
class foo:
bar = 5
def __init__(self, a):
self.x = a
def spam(self):
print(self.x)
class baz(foo):
def __init__(self, a):
self.b = a
b = baz(5)
b.spam()
the script gives me an error: AttributeError: 'baz' object has no attribute 'x'.
So this would suggest, that if my class has a default __init__, it also has an explicit super() call. I couldn't actually find any info confirming this, so I just wanted to ask if I am correct.
The problem is that when you define the method __init__ in your subclass baz, you are no longer using the one in the parent class foo. Then, when you call b.spam(), x does not exist because that is define in the __init__ method of the parent class.
You can use the following to fix this if what you want is to call the __init__ method of the parent class and also add your own logic:
class baz(foo):
def __init__(self, a):
super().__init__(10) # you can pass any value you want to assign to x
self.b = a
>>> b = baz(5)
>>> b.spam()
10

Can I call a subclass from a parent class to create the object

For example:
class parent(self):
def __init__(self, i):
self.i = i
def something(self, value):
a = child(value)
return a
class child(parent):
def something_that_is_not_init(self):
return self.i
The child class inherits init from the parent class. So my question is, in my parent class, can I create an instance of the child object, use and return it?
I would execute it as following:
a = parent(2)
b = a.something(3)
b.something_that_is_not_init()
3
Edited question a bit, updated code section since the question wasn't clear.
Yes, it's valid, but I don't recommend it. It's generally considered bad OOP programming. Also, you can create it as a static method so you never actually have to instantiate the parent class.
class parent():
def __init__(self, i):
self.i = i
#staticmethod
def foo(i):
c = child(i)
return c
class child(parent):
def bar(self):
print("Lucker number {}.".format(self.i)) # just to show the parent __init__ function is called
c = parent.foo(7)
c.bar() #=> Lucky number 7.
I just tried your example (including some missing self) and with python3 at least it works:
class Parent():
def __init__(self):
pass
def something(self):
a = child()
return a
class Child(parent):
def something_that_is_not_init(self):
print('yes, you got me')
and calling the something method works:
print(parent().something().__class__.__name__)
# Child
parent().something().something_that_is_not_init()
# yes, you got me
But maybe that's not very good design. Consider a factory or using __new__. But since you explicitly stated you wanted something like this: It works, even though I feel slightly spoiled writing it :-)

Categories

Resources