So, last time, I wrote an article focusing on the one word computer programs don't know is a word: Polymorphism. Well, before I started talking about it, I mentioned something called inheritance. Let's get to that!
Inheritance: class.__init__(self, classValue)
Explaining inheritance is a little difficult, as those bold words make no sense, really. Well, we all know what inheritance is. It's what you get from someone else, like red hair from your parents, or maybe the family income, or whatever.
Well, the programming term is like that. A class inherits attributes/methods from another class. Well, since it's Thanksgiving, I'll give an example related to that holiday. Let's say we were making a game. In this game, you could collect items, like turkeys, coins, pilgrim hats, etc. When the player touches the coin (or turkey/pilgrim hat), there would be a pickUp() method triggered, and it would be added to their bag or whatever is storing everything. We should also have the coins be used to buy things at shops. Well, here is what we might do.
class GameObject: #this is the variable of all the items picked up
def __init__(self, name):
self.name = name #name is changed to one of the item classes
def pickUp(self, player): #here's the function that lets the player pick up the item
#insert code here to add the object
#to the player's bag
class Coin(GameObject): #this is known as a subclass, which inherits the attributes (etc.) of a class
def __init__(self, value):
GameObject.__init__(self, "coin") #this is what changes name to coin!
self.value = value
def spend(self, buyer, seller):
#insert code here to remove the coin from buyer and give to seller
Well, this obviously won't work, since we don't have all of the mechanics required to make a game using these objects. You'll just get an error trying to run it.
Well, this is my example of inheritance. Happy Thanksgiving!
No comments:
Post a Comment