Inheriting function data - python

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()

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'>

Related

Change a self attribute only for one object in a class in Python

I'm stuck on a problem in Python... (i'm an absolute beginner but i need to do a little
environmental science model..)
so the problem is I have:
class C:
def __init__(self, x, y, z):
self.x = x
self.y = self.x * 8
self.z = self.y * 9 + 0.5
self.w = self.z +2
one = C(5,8,12)
two = C(2,12,12)
three = C(1,2,3)
So... i want to change the self.z but only for the object three
(i want it to be self.z = 12 * self.x );
I have to call it in self.w so i can't modify it after my istances...
do you have any suggestion to a beginner?
Thank you so much and have a nice day!
A few notes. First you are not actually using the arguments of y or z that are passed in __init__(self, x, y, z).
To allow on the fly overloading, you may want to break out the individual assignments into their own methods so it is easier to change the behavior you want.
Below you can pass in a custom function that will be applied to the x value when calculating z.
class C:
def __init__(self, x, custum_fn_z=None):
self.x = x
self.y = self.calc_y()
self.z = self.calc_z(custum_fn_z)
self.w = self.calc_w()
def calc_y(self):
return self.x * 8
def calc_z(self, custom_fn_z=None):
if custom_fn_z:
return custom_fn_z(self.x)
return self.y * 9 + 0.5
def calc_w(self):
return self.z +2
to use it:
one = C(5)
two = C(2)
three = C(1, lambda x: 12*x)

Can One Write Methods for Three Instances of Same Class

I ask this question out of curiosity, there are probably many workarounds to what I am about to ask.
When you create a class in python, you can define methods that take two instances of this class, by the use of "self" and "other" keywords, such as
class MyClass():
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
Can you do the same with 3 or more instances of the same class? That is, is there something like "self", "other", "another"?
You can create a list that contains the arguments of different class instances that can be called from a loop.
class MyClass():
def __init__(self, x):
self.x = x
def __add__(self, others):
temp = self.x
for obj in others:
temp += obj.x
return temp
x = MyClass(5)
y = MyClass(5)
z = MyClass(5)
print(x.__add__([y, z])) # 15

Python Classes using __init and __repr__ methods

Iam trying to create a class that should accept two arguments, x and y, and be represented by a string 'Point(x, y)' with appropriate values for x and y
class Point(object):
def __init__(self, x, y):
self.x = 0
self.y = 0
def __repr__(self):
return "Point(%s,%s)"%(self.x, self.y)
Error:
Point(0,0) is not of type 'string'
Failed validating 'type' in schema['items']:
{'type': 'string'}
On instance[0]:
Point(0,0)
"self.x" is the value of the instance of your class. So, if you set "self.x = 0", it means whenever you create an object for that class, the "x" value of that object will always be 0 instead of what you pass in the parameter.
"x" is the value of what you pass in the parameter.
self.x = x
self.y = y
Code:
class MyClass():
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point(%s,%s)"%(self.x, self.y)
thiss = MyClass(0, 0)
print(thiss.__repr__())
thiss = MyClass(20, 20)
print(thiss.__repr__())
Output:
daudn$ python3 point.py
Point(20,20)
daudn$ python3 point.py
Point(0,0)
When declaring your init function, you initialized self.x and self.y to always be 0. If you look at the code I've posted, whatever number you pass to the class will become the values or Point.

Can't access instance attributes

I try to use the composition relationship but I can't access to the compound class A:
with this code I'm trying to add to the list of class A, an object from the class B.
class B:
def __init__(self,X,Y,Z):
self.X
self.Y
self.Z
def Xreturner(self):
return self.X
def Yreturner(self):
return self.Y
def Zreturner(self):
return self.Z
class A:
def __init(self):
self.lst=[[1,2,3],[3,4,5],]
self.b=B()
def add(self): # trying to add b object to the list
self.lst.append(self.b)
#### TEST####
objA=A()
objA.add(6,7,8)
When I test I get this error:
Traceback (most recent call last):
File "home/testXYZ.py", line 28, in <module>
objA.add(6,7,8)
TypeError: add() takes exactly 1 argument (4 given)
Please help me to solve this.
The statement self.X in the __init__ method of B does nothing. You need to put self.X = X.
You are passing parameters to add() but it doesn't take any parameters. Maybe you want to add parameters (in the same way you have some for __init__ of X.
Maybe you even want to pass parameters to the __init__ of A (instead of to A). Then you can pass those to the constructor of B.
First, your class B initializer is incorrect:
class B:
def __init__(self, x, y, z): # <== should use snake_case for vars
self.x = x
self.y = y
self.z = z
Next, your class A add should create a new B object and add to the list:
def add(self, x, y, z):
new_b = B(x, y z)
self.lst.append(new_b)

Python object #property

I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why.
class Point:
def __init__(self, coord=None):
self.x = coord[0]
self.y = coord[1]
#property
def coordinate(self):
return (self.x, self.y)
#coordinate.setter
def coordinate(self, value):
self.x = value[0]
self.y = value[1]
p = Point((0,0))
p.coordinate = (1,2)
>>> p.x
0
>>> p.y
0
>>> p.coordinate
(1, 2)
It seems that p.x and p.y are not getting set for some reason, even though the setter "should" set those values. Anybody know why this is?
The property method (and by extension, the #property decorator) requires a new-style class i.e. a class that subclasses object.
For instance,
class Point:
should be
class Point(object):
Also, the setter attribute (along with the others) was added in Python 2.6.
It will work if you derive Point from object:
class Point(object):
# ...

Categories