Python Forum
A problem with child class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: A problem with child class (/thread-11285.html)



A problem with child class - Truman - Jul-01-2018

class Dog():
	species = 'mammal'
	
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	def description(self):
		return f'{self.name} is {self.age}'
		
	def speak(self, sound):
		return f'{self.name} says {self.age}'
	
class RussellTerrier(Dog):
	def run(self, speed):
		return f'{self.name} runs {self.speed}'
	
class Bulldog(Dog):
	def run(self, speed):
		return f'{self.name} runs {self.speed}'
	
jim = Bulldog("Jim", 12)
print(jim.description())
	
print(jim.run("slowly"))
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\dogparent.py", line 25, in <module> print(jim.run("slowly")) File "C:\Python36\kodovi\dogparent.py", line 20, in run return f'{self.name} runs {self.speed}' AttributeError: 'Bulldog' object has no attribute 'speed'
I don't understand these errors:
1. Child classes have specific attributes and behaviors as well
2. Bulldog object has 'speed' within method run


RE: A problem with child class - gontajones - Jul-02-2018

You can add the speed at the __init__() or maybe just use it in the run().

def __init__(self, name, age):
        self.name = name
        self.age = age
        self.speed = 'Normal'
Then..

class Bulldog(Dog):
    def run(self, speed):
        self.speed = speed
        return f'{self.name} runs {self.speed}'
Or

class RussellTerrier(Dog):
    def run(self, speed):
        return f'{self.name} runs {speed}'



RE: A problem with child class - ichabod801 - Jul-02-2018

The speed in the run method is not an attribute of the class, it is a parameter to the method. You would only use self-dot for an attribute, like name. speed you would just reference by itself, like a parameter to a function. This should work:

def run(self, speed):
        return f'{self.name} runs {speed}'