这里用一个简单的实例来说明:
class Character:
def __init__(self, name, initial_health):
self.name = name
self.health = initial_health
self.inventory = []
def __str__(self):
s = "Name: " + self.name
s += " Health: " + str(self.health)
s += " Inventory: " + str(self.inventory)
return s
def grab(self, item):
self.inventory.append(item)
def get_health(self):
return self.health
def example():
me = Character("Bob", 20)
print str(me)
me.grab("pencil")
me.grab("paper")
print str(me)
print "Health:", me.get_health()
example()
运行结果
Name: Bob Health: 20 Inventory: []
Name: Bob Health: 20 Inventory: ['pencil', 'paper']
Health: 20
——来自 coursera The Rice的课程 An Introduction to Interactive Programming in Python (Part 2) —Object-oriented Programming