Objects in Python 3
- Class: a template
- Attribute: a variable within a class
- Method: a function within a class
- Object: a particular instance of a class
- Constructor: code that runs when an object is created
- Inheritance: the ability to extend a class to make a new class
Creating Objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class : x = 0
def party(self): self.x = self.x + 1 print('So far', self.x)
an = PartyAnimal()
an.party() an.party() an.party()
|
Inheritance
Put the class in the subclass.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class : x = 0 name = ""
def __init__(self, newName): self.name = newName print(self.name, "Constructed")
def party(self): self.x = self.x + 1 print('So far', self.x)
class FootballFan(PartyAnimal):
points = 0
def touchdown(self): self.points = self.points + 7 self.party() print(self.name, 'points', self.points)
s = PartyAnimal("Sally") s.party()
j = FootballFan("Jim") j.party() j.touchdown()
|
近期评论