'Inheriting function data
I have a question about inheriting data from functions, defined inside another class. I have written an example script to clarify myself. In this script I define a class called Test. Here I define x and y in the __init__() function. Thereafter, I make a calculation and return x,y. I then create another class called Inherit_Test that inherits the x,y from Test. In this class I define z and make a calculation with the inherited values from Test. Afterwards, I call the class with Values. The problem arises when I want to access the data stored in Values. The type of this object is "Inherited_Values", while you would expect the type to be int and have the value 3*4*43. I hope I have explained myself well enough, thanks!
class Test():
def __init__(self, x , y ):
self.x = x
self.y = y
def Calculation(self):
self.x = 3*4 #self.x*self.x
self.y = 43 #self.y*self.y
return self.x, self.y
class Inherit_Test(Test):
def __init__(self,z ):
Test.__init__(self, x = Test.Calculation(self)[0],
y = Test.Calculation(self)[1])
self.z = z
def Inherit_Calculation(self):
self.z = self.x * self.y
return self.z
Value = Inherit_Test(0)
Value.Inherit_Calculation()
Solution 1:[1]
unfortunately, your question is not very clear defined and it is hard to assume what you exactly wanted to do. I'll try to help you with the following code :
class Test():
def __init__(self):
self.Calculation() # instantiation of the self.x and self.y; no init params needed
def Calculation(self):
self.x = 3*4 #self.x*self.x
self.y = 43 #self.y*self.y
#return self.x, self.y # do you need to return something here ?
class Inherit_Test(Test):
def __init__(self):
super().__init__() # instantiation of the parameters of your super class
#self.z = z # do you need this part ?
def Inherit_Calculation(self):
self.z = self.x * self.y
return self.z
Result:
Value = Inherit_Test()
print(type(Value.Inherit_Calculation()))
print(Value.x)
print(type(Value.x))
print(Value.y)
print(type(Value.y))
print(Value.z)
print(type(Value.z))
<class 'int'>
12
<class 'int'>
43
<class 'int'>
516
<class 'int'>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | baskettaz |
