Python inherit variables from parent class - python

Sorry if I don't explain it that well but I'll try my best:
So I want to inherit the variables from the Parent class, but I don't want to pass them again when creating an instance of the Child class because I think that is redundant. I just want to use the eye color from the Parent for example. See the example code below for what I mean
This is what works:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, eye_color, length):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men", "Blue", 2)
print(x.eye_color, x.length)
print(y.gender, x.length)
This is what I somehow want:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)

What you ask does not make sense:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)
In child, the parameters eye_color and length come from nowhere.
rassar example is good if you want to reuse a parent object.
You can also do the following:
class Parent:
# def __init__(self, eye_color=(default value here), length=(default value here)):
def __init__(self, eye_color="", length=0):
self.eye_color = str(eye_color)
self.length = length
OR
class Parent:
def __init__(self, eye_color="", length=0):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, *args, **kwargs):
super().__init__(*args, **kwargs)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men") # Work with first example of Parent
y = Child("Men", eye_color="Blue", length=2) # Work with first
y = Child("Men", "Blue", 2) # Work with second example
print(x.length, x.eye_color)
print(y.gender, y.length)

You could try passing a Parent instance to the Child initializer...That's probably the closest you'll get.
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, parent):
super().__init__(parent.eye_color, parent.length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men", x)
print(x.length, x.eye_color)
print(y.gender, x.length)
Another thing you could do is hold a last_parent variable:
global last_parent
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
last_parent = self
class Child(Parent):
def __init__(self, gender):
super().__init__(last_parent.eye_color, last_parent.length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)

Related

How to access the stored array in class

I want to access the array i have filled throughout the for loop,however what i get it is still empty array when call fill_particles().particles, is there any way to get rid of this problem? here is my code.
class particle(object):
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class fill_particles():
def __init__(self):
self.particles=[]
def fill(self):
for i in range(5):
self.particles.append(particle(i,i+1,i+2))
You need to instantiate the class and call fill(). Here's a working example, along with extra functions for display purposes:
class Particle(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f'Particle(x={self.x}, y={self.y}, z={self.z})'
class Particles:
def __init__(self):
self.particles = []
def fill(self):
for i in range(5):
self.particles.append(Particle(i, i + 1, i + 2))
def __repr__(self):
return f'Particles({self.particles!r})'
particles = Particles()
print(particles)
particles.fill()
print(particles)
Output:
Particles([])
Particles([Particle(x=0, y=1, z=2), Particle(x=1, y=2, z=3), Particle(x=2, y=3, z=4), Particle(x=3, y=4, z=5), Particle(x=4, y=5, z=6)])

How do I add arguments to a subclass in Python 3

class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color):
self.color = color
fido = Dog(legs = 4, color = "brown")
This would spute out an error message. How would I do something like that where I add parameters to the subclass that doesn't pertain to the superclass.
Try this:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, legs, color):
super().__init__(legs)
self.color = color
fido = Dog(legs=4, color="brown")
That's not how inheritance works. When you inherit from another class, the super-class's parameters are not automatically added to the sub-class's parameter list. You must explicitly accept the desired parameters in your sub-class's constructor and pass them on to the super class's constructor:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color, legs):
super().__init__(legs)
self.color = color
fido = Dog(legs = 4, color = "brown")
Here's an example from a tutorial which explains inheritance and shows how to do this. You need to call the parent class's init function as in this similar example from this tutorial:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
class Dog(Pet):
def __init__(self, name, chases_cats):
Pet.__init__(self, name, "Dog")
self.chases_cats = chases_cats
def chasesCats(self):
return self.chases_cats
You still have to pass in the legs argument for Dog, and then use super:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color, legs):
super().__init__(legs)
self.color = color
fido = Dog(legs = 4, color = "brown")

use variable in class A in class B by using A.__init__() method

I'm trying to use a variable in class A in class B by using __init__() method. But somehow the variable in class A and B couldn't show up (no change in my cvs write file). Here is my code:
class Welcome(object):
csv_name_sub = None
csv_name_ses = None
def __init__(self, master, csv_name_sub = None, csv_name_ses = None):
self.entrySub=Entry(self.master,bg="grey")
self.entrySes=Entry(self.master,bg="grey")
self.csv_name_sub = str(self.entrySub.get())
self.csv_name_ses = str(self.entrySes.get())
def writeToFile(self):
with open("/Users/Desktop/" + self.csv_name_sub+ '_' + self.csv_name_ses + '_subjectNo.csv',
'w') as resultFile:
resultFileWrite=....
class App(Welcome):
def __init__(self, master):
Welcome.__init__(self, master) #I'm using python 3.5
Welcome.csv_name_sub = str(self.entrySub.get())
Welcome.csv_name_ses = str(self.entrySes.get())
print('session is', Welcome.csv_name_ses)
print("subject is", Welcome.csv_name_sub)
self.resultFile = open("/Users/Desktop/" + Welcome.csv_name_sub + '_' + Welcome.csv_name_ses + '_results.csv', 'w')
The program can be run without an error, but csv_name_sub and csv_name_ses is empty when I print them in these two classes.
The updated attributes are bound to the instance not the superclass. You should reference the attributes via the instance using self:
class App(Welcome):
def __init__(self, master):
Welcome.__init__(self, master) # Updated attributes are bound to self
self.csv_name_sub = str(self.entrySub.get())
self.csv_name_ses = str(self.entrySes.get())
...
Use the attributes of the instance, i.e. from self:
class App(Welcome):
def __init__(self, master):
super().__init__(master) #I'm using python 3.
print('session is', self.csv_name_ses)
print("subject is", self.csv_name_sub)
Working example:
class Entry(object):
def __init__(self, master, bg):
pass
def get(self):
return 42
class Welcome(object):
def __init__(self, master):
self.master = master
self.entrySub = Entry(self.master, bg="grey")
self.entrySes = Entry(self.master, bg="grey")
self.csv_name_sub = str(self.entrySub.get())
self.csv_name_ses = str(self.entrySes.get())
class App(Welcome):
def __init__(self, master):
super().__init__(master)
print('session is', self.csv_name_ses)
print("subject is", self.csv_name_sub)
app = App('x')
Output:
session is 42
subject is 42

How to add additional attributes to a class?

How would I add additional locationx and locationy variables to the lists while the program is running?
Example of the class:
class Building:
'Common base class for all buildings'
def __init__(self, name, hp, img, locationx, locationy, height, width):
self.name = name
self.hp = hp
self.img = img
self.locationx = locationx
self.locationy = locationy
self.height = height
self.width = width
building_shipyard = Building("Shipyard",500,shipyard,[1000,2500,5000],[1000,2500,5000],300,300)
For instance, after a user places a new building, I might want self.locationx and self.locationy to be updated from [1000,2500,5000] to [1000,2500,5000,7000].
Just access these attributes:
...
def place_building ():
global building_shipyard
...
building_shipyard.locationx = [1000,2500,5000,7000]
# or
building_shipyard.locationx.append(7000)

Python 3x class methods

I'm currently learning the basics of classes, and I came up with some basic code as follows:
class shape(object):
def __init__(self, num_sides, type):
self.num_sides = num_sides
self.type = type
class square(shape):
def __init__(self, side_length):
self.num_sides = 4
self.type = 'regular quadrilateral'
self.side_length = side_length
def perim():
return side_length * 4
def area():
return side_length ** 2
class circle(shape):
def __init__(self, radius):
self.num_sides = 1
self.type = 'ellipsis'
self.radius = radius
Now, when I type the following:
shape1 = square(5)
shape1.perim()
I get the following output:
<bound method square.perim of <__main__.square object at 0x0000000003D5FB38>>
What is this? How can I get python to actually return the perimeter of the square?
Also, I have another question:
Do any class methods exist other than __init__() and __str__()? If so, can you please list them so I can go off and research them?
as shown, you are going to have some problems with this. If you are trying to have circle and square be subset set classes of shape, then the two sub classes need to be indented. Also, on class circle and square, you really do not need the (shape). also note the things I commented out as not needed.
This does not come out as I am posting it. the class shape (object):does not show up and the subclasses are not indented and I can not seem to make it show up
class shape(object):
def init(self, num_sides, type):
#self.num_sides = num_sides
self.type = type
class square:
def __init__(self, side_length):
#self.num_sides = 4
#self.type = 'regular quadrilateral'
self.side_length = side_length
def perim(self):
return self.side_length * 4
def area(self):
return self.side_length ** 2
class circle:
def __init__(self, radius):
#self.num_sides = 1
#self.type = 'ellipsis'
self.radius = radius
def area (self):
return 3.14 * self.radius ** 2
shape2 = circle (5)
print ('test of circle: ',shape2.area ())
shape1 = square(5)
print('test of square: ', shape1.perim())
Two things, indentation of the init of shape and add self. to the perim and area methods.
class shape(object):
def __init__(self, num_sides, type):
self.num_sides = num_sides
self.type = type
class square(shape):
def __init__(self, side_length):
self.num_sides = 4
self.type = 'regular quadrilateral'
self.side_length = side_length
def perim(self):
return self.side_length * 4
def area(self):
return self.side_length ** 2
class circle(shape):
def __init__(self, radius):
self.num_sides = 1
self.type = 'ellipsis'
self.radius = radius
shape1 = square(5)
print( shape1.perim())
Access instance variable with self
class square(shape):
def __init__(self, side_length):
self.num_sides = 4
self.type = 'regular quadrilateral'
self.side_length = side_length
def perim(self):
return self.side_length * 4
def area(self):
return self.side_length ** 2

Categories