I apologize if this has been answered, but I've search everywhere and cannot seem to find an answer. Say I have a class Dog. That class has two objects, Buster and Bowser. What would be the best way to create methods specific to each object?
For instance, if I wanted to create roll_over() and play_dead() methods that only Buster can do, and stand() and high_five() methods that only Bowser can do, what would be a good way to do that?
Additionally (this might need to be its own question), how could I give these methods user-readable names so that if they were using Buster, they could see options to make him "Roll over" or "Play dead", and so on for Bowser?
Thank you.
2 Answers 2
You make a dog class and then make new classes inheriting from the "parent" class.
class Dog():
def __init__(self):
#Put things here that all dogs can do
#...
class Buster(Dog):
def __init__(self):
#...
def roll_over(self):
#...
def play_dead(self):
#...
class Bowser(Dog):
def __init__(self):
#...
def stand(self):
#...
def high_five(self):
#...
Basically, you're creating a "parent" class, which each of the "children" classes (aka Buster, Bowser) inherit from. They get all the features of the "parent" but can add their own separate functions. That is how you do it easily.
You can create the new Buster and Bowser objects with buster = Buster() and bowser = Bowser.
If you have further questions, ask below. Good luck!
3 Comments
buster = Buster(...), etc.?The question is a bit contrived, so it's hard to say how I would implement this in real-life. (These dogs are unlikely to show up in a business scenario).
Here, we allow for the fact that there are dogs and there are things that roll over. They overlap, but there may be things that roll over that are not dogs just as there may be things that are dogs that do not roll over. In some programming languages this would be called a trait, but in Python it's usually implemented with multiple inheritance.
class Dog():
'''
Maybe all dogs are created with the potential
to roll over and play dead, but need to be trained!
You can define properties that all dogs have here, or you can leave it
as a "marker" class that just indicates that subclasses are indeed dogs.
'''
class Roller():
'''May not be a dog, but can definitely roll over'''
def roll_over(self):
print('Slow your roll, dawg!')
class NotDeadYet():
'''No you're not, you'll be stone dead in a moment.'''
def play_dead(self):
print("I think I'll go for a walk.")
class Buster(Dog, Roller):
'''I'm a dog and a roller!'''
class Bowser(Dog):
'''Just a dumb dog'''
class Dug(Dog):
def __init__(self):
print('My name is Dug. I have just met you, and I love you.')
def speak(self):
print('SQUIRREL!')
buster = Dog(); def roll_over(self): print "Rolling over!"; buster.roll_over = roll_over(put newlines after the;s). Is that what you're looking for?buster.roll_over = roll_overline works?