Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 A problem with child class
#1
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
Quote
#2
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}'
Truman likes this post
Quote
#3
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}'
Truman likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Class Problem scratchmyhead 3 111 Nov-19-2019, 08:28 AM
Last Post: Larz60+
  XML Parsing Child karthi_python 1 236 May-16-2019, 01:37 PM
Last Post: karthi_python
  logging: child module unable to get parent config jerryxiao 3 400 Apr-09-2019, 04:17 AM
Last Post: jerryxiao
  problem with class method AmirAB 3 391 Feb-13-2019, 01:51 AM
Last Post: AmirAB
  Error when creating child process on Windows 10 Charles 0 855 May-30-2018, 01:24 PM
Last Post: Charles
  parent/add and child/div PyMan 1 530 Feb-23-2018, 04:38 PM
Last Post: nilamo
  problem with simple class code diegoraffo 5 1,098 Jan-27-2018, 02:31 AM
Last Post: ka06059
  Trying to create a child class in Python 2.7 mac77 1 1,085 Sep-27-2017, 06:15 PM
Last Post: nilamo

Forum Jump:


Users browsing this thread: 1 Guest(s)