adding two value in a class in python - python

I am knew at this and not sure the exact syntax to use to add x,y in python using this class definition
class Add(values):
def __init__(self, x, y):
values.__init__(self, [x, y])
def forward(self):
return self.values[x] + values[1]
I am not able to figure out how to access x,y to add them together. I have tried all the possibilities that I can think of. Thank you.

I think you want a function and not a class.
def add(x, y):
return x+y
If you're sure that this really has to be a class for whatever you're doing, it can look like this:
class Add:
def __init__(self, x, y):
self.x = x
self.y = y
def forward(self):
return self.x+self.y
Then
>>>add(5, 6)
11
>>>a = Add(5, 6)
>>>a.forward()
11

i think that is what you need
class Values():
def __init__(self, x = 0, y=0):
self.x_value = x
self.y_value = y
class Add(Values):
def __init__(self, x = 0, y=0):
Values.__init__(self, x, y)
def forward(self):
return (self.x_value + self.y_value)
add = Add(x = 20, y=20)
print (add.forward())

To add something to other answers, I would say that :
class Add(values):
means that you create class 'Add' who inherits from the class 'values'. Class 'values' must be defined somewhere otherwise you will have the NameError.
More info about inheritance here :
https://docs.python.org/3.6/tutorial/classes.html#inheritance

Actually the answer I was looking for is :
self.x =[0]
self.y = [1]
Thanks for the tries.

Related

How do I only inherit some variables from a super class in Python

I am trying to make a subclass, Square, from a superclass, Shape.
class Shape :
def __init__ (self, x, y) :
self.x = x
self.y = y
self.description = "This shape has not been described yet"
def area (self) :
return self.x * self.y
def describe (self, text) :
self.description = text
I have tried
class Square (Shape) :
def __init__ (self, x) :
self.x = x
self.y = x
self.description = "This shape has not been described yet"
which seems to work, but the only thing that actually changes in Square is self.y = x, so I wonder if I could do the same thing without having to write self.x and self.description again.
(I tried doing something like this:
class Square (Shape) :
def __init__ (self, x) :
self.y = x
super().__init__()
but, when I create a Square object, a type error occurs:
TypeError: init() missing 2 required positional arguments: 'x' and 'y')
A Square is a Shape whose x and y are the same. Hence:
class Square(Shape):
def __init__(self, x):
super().__init__(x, x)
You just need to call Shape.__init__(self, x, y) with your x as both the x and y parameters.
Just call the super function inside __init__. Put both the arguments equal to x.
class Square(Shape):
def __init__(self, x):
super().__init__(x, x)

How can i use a function inside of another function

I am currently playing around with classes and functions since i am not familiar with python and i would like to know how i can get addy(self, addx) to call addx.
class test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self, addx):
z = addx() + 10
return z
one = test(1)
print(one.addy())
line 15, in print(one.addy()) TypeError: addy() missing 1
required positional argument: 'addx' Process finished with exit code 1
You need to call self from within a class method.
self.addx()
Also the addx parameter on this line shouldn't be there:
def addy(self, addx):
I think this is what you are going for:
class test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self):
z = self.addx() + 10
return z
one = test(1)
print(one.addy())
You've overcomplicated things by wrapping it in a class. Take it out and it'll work (mostly) the way you expect.
def add10(x):
return x+10
def add20(x):
return add10(add10(x))
Since you've wrapped it in the class you've complicated the namespace. It's no longer called addx or addy, so using those names throws a NameError. You have to use the qualified name instead.
class FooBar():
def __init__(self):
self.x = 10
def addx(self):
return self.x + 10 # Note the `self.` before the attribute...
def addy(self):
return self.addx() + 10 # ...and also before the method name.
Methods are always passed their owning object as a first argument when called, which is why we've got def addx(self): but then call with self.addx()
If you are attempting to relate addx in the signature of addy to the method addx, you can pass the string name of the method and use getattr:
class Test:
def __init__(self, x):
self.x = x
def addx(self):
y = self.x + 10
return y
def addy(self, func):
z = getattr(self, func)() + 10
return z
s = Test(3)
print(s.addy('addx'))

preferred way to modify attributes

I'm using a helper method in my class to modify an attribute, and can see several ways to do this. Are any of the following helper and associated methods preferred or avoided for good reason?
class Test(object):
def __init__(self, x, y):
self.x = x
self.y = y
def _x_helper1(self):
self.x += self.y
def method1(self):
# some other code...
self._x_helper1()
def _x_helper2(self, y):
# some other code...
self.x += y
def method2(self):
# some other code...
self._x_helper2(self.y)
def _x_helper3(self, y):
# some other code...
return y
def method3(self):
# some other code...
self.x += self._x_helper3(self.y)
This example is way too abstract.
Nothing is wrong with just adding obj.x + obj.y. If you need to mutate object's state, and you mutate based on attributes only, use
def mutate(self):
self.x += self.y

Which is the better way to inheritance?

Is there any difference between this:
class Vehicle():
def __init__(self, x, y):
self.y = y
self.x = x
class Car(Vehicle):
def __init__(self, x, y):
Vehicle.__init__(self, x, y)
class Scooter(Vehicle):
def __init__(self, x, y):
Vehicle.__init__(self, x, y)
and this:
class Vehicle():
def __init__(self, x, y):
self.y = y
self.x = x
class Car(Vehicle):
pass
class Scooter(Vehicle):
pass
Because without def __init__ in child classes I got the same thing, I mean __init__ doesn't provide any effect.
You should't do either of them. The best way to do it is using super.
class Vehicle():
def __init__(self, x, y):
self.y = y
self.x = x
class Car(Vehicle):
def __init__(self, x, y):
super(Car, self).__init__(x, y)
# super().__init__(x, y) # for python3
Check this blog post by Raymond Hettinger (core python contributor) on why you should be using super
You need __init__ method when you want to do child specific initialisation. Assume your child classes require another argument to be passed to the constructor and is unique to that class, in that case __init__ method is really required.
class Vehicle():
def __init__(self, x, y):
self.y = y
self.x = x
class Car(Vehicle):
def __init__(self, x, y, z):
Vehicle.__init__(self, x, y)
self.z = z
class Scooter(Vehicle):
def __init__(self, x, y, z):
Vehicle.__init__(self, x, y)
self.z = z
I think this would be best explained with an example.
Now take this scenario:
>Vehicle ---> Car,Bike,Boat,Aeroplane,Train
>[All are vehicles right]
>Things they have in common would be (say for ex.) **Price** and **Color**
However things they won't have in common would be?
>**Wheels**. The total number of wheels may differ.
>
> Car-4 Bike-2 Boat-0 Aeroplane-(**Not sure**) Train-(**Many I
guess**?)
But you get the point right? So When I want to just have a Vehicle object I don't want (or I can't tell the number of wheels) In that case I can initialize only with just price and color
However when I know the specific type of Vehicle say Car now I can __init__ it with number of wheels. Now this is where object specific initializations play a major role.
A full example code of the above sample:
class Vehicle():
def __init__(self, x, y):
self.color = y
self.price = x
def Horn(self):
print("Pommm...Pommmmm!!")
class Car(Vehicle):
def __init__(self, x, y,wheel):
Vehicle.__init__(self, x, y)
self.wheel = "Four Wheels man: 4"
class Scooter(Vehicle):
def __init__(self, x, y,wheel):
Vehicle.__init__(self, x, y)
self.wheel = "Just Two man : 2"
VehObj = Vehicle("5000$","Black")
VehObj.Horn()
print(VehObj.color,VehObj.price)
#However note this
carObj = Car("5000$","Black",4)
print(carObj.color,carObj.price,carObj.wheel)
#Look at this
sObj = Scooter("5000$","Black",2)
print(sObj.color,sObj.price,sObj.wheel)
Output:
Pommm...Pommmmm!!
Black 5000$
Black 5000$ Four Wheels man: 4
Black 5000$ Just Two man : 2
Hope that cleared you up.
If you don't provide an __init__ method in the child classes, they will just use the __init__ method defined in their parent class (aka inheritance). In the former case, you are overriding the __init__ method for the child classes but you are simply calling the __init__ method of the parent class. So if you don't do that (like the later case) it will be the same. The later case automatically inherits the __init__ method.
Other ways to write the same thing would be:
class Car(Vehicle): #This is the best way to do it though
def __init__(self, x, y):
super()__init__(x, y)
Or
class Car(Vehicle):
def __init__(self, x, y):
self.x = x
self.y = y
TLDR; They are equivalent.
Calling the init method of super class is optional if you don't wont to edit the __init__ method of superclass.
but if you want to edit the superclass method you need custom init
class Vehicle():
def __init__(self, x, y):
self.y = y
self.x = x
class Car(Vehicle):
def __init__(self, x, y, z):
Vehicle.__init__(self, x, y)
self.z = z

Redirect class variable to class function

Let's take a simple class as an example:
class Vector:
def __init__(self):
self.x = 1
self.y = 1
self.z = 1
What I would like is to give this class a variable called sum such that when I do
v = Vector()
v.sum
I am given the sum x+y+z (in this case 3). Of course I can easily just make a class method that does this, but then I would have to write v.sum() instead of v.sum. Is there any way to hide the fact that the class actually calls a function when asking for a variable?
Thanks in advance.
class Vector(object): # subclass object for new style class
def __init__(self):
self.x = 1
self.y = 1
self.z = 1
#property
def sum(self):
return self.x + self.y + self.z
>>> v = Vector()
>>> v.sum
3
http://docs.python.org/2/library/functions.html#property

Categories

Resources