Python Forum
Some questions regarding classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some questions regarding classes
#1
task:
Create a Pets class that holds instances of dogs; this class is completely separate from the Dog class. In other words, the Dog class does not inherit from the Pets class. Then assign three dog instances to an instance of the Pets class.

solution:
# Parent class
class Dog:

    # Class attribute
    species = 'mammal'

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance method
    def description(self):
        return "{} is {} years old".format(self.name, self.age)

    # instance method
    def speak(self, sound):
        return "{} says {}".format(self.name, sound)

# Child class (inherits from Dog class)
class RussellTerrier(Dog):
    def run(self, speed):
        return "{} runs {}".format(self.name, speed)

# Child class (inherits from Dog class)
class Bulldog(Dog):
    def run(self, speed):
        return "{} runs {}".format(self.name, speed)
		
# Parent class
class Pets:
	
	dogs = [] 
	
	def __init__(self, dogs):
		self.dogs = dogs

my_dogs = [
    Bulldog("Tom", 6),
	RussellTerrier("Fletcher", 7),
	Dog("Larry", 9)
]

# Instantiate the Pets class
my_pets = Pets(my_dogs)
print(f'I have {len(my_pets.dogs)} dogs.')
for dog in my_pets.dogs:
	print(f'{dog.name} is {dog.age}')
print(f'And they\'re all {dog.species}s, of course.')
I have several questions regarding this solution:
1. why in class Pets it is necessary to open an empty list
dogs = []
2. this line confuses me:
print(f'I have {len(my_pets.dogs)} dogs.')
why my_pets.dogs? I don't see a connection. dogs is attribute of the class Pet. Does dogs represents names in my_dogs list methods?
3. in
for dog in my_pets.dogs:
what is dog? Doh
Reply


Messages In This Thread
Some questions regarding classes - by Truman - Jul-04-2018, 10:36 PM
RE: Some questions regarding classes - by snippsat - Jul-05-2018, 12:32 AM
RE: Some questions regarding classes - by Truman - Jul-05-2018, 10:08 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 09:54 AM
RE: Some questions regarding classes - by Truman - Jul-06-2018, 09:11 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 09:45 PM
RE: Some questions regarding classes - by Truman - Jul-06-2018, 10:00 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 10:14 PM
RE: Some questions regarding classes - by Truman - Jul-07-2018, 11:08 PM
RE: Some questions regarding classes - by Truman - Jul-08-2018, 10:36 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020