第一个简单的类
class FirstClass: #Define a class object
def setdata(self, value): #Define class methods
self.data = value #self is the instance
def display(self):
print(self.data) #self.data: per instance
测试结果:
继承
class FirstClass: #Define a class object
def setdata(self, value): #Define class methods
self.data = value #self is the instance
def display(self):
print(self.data) #self.data: per instance
class SecondClass(FirstClass): #Inherits setdata
def display(self): #Changes display
print('Current value = "%s"' % self.data)
测试结果:
运算符重载
class FirstClass: #Define a class object
def setdata(self, value): #Define class methods
self.data = value #self is the instance
def display(self):
print(self.data) #self.data: per instance
class SecondClass(FirstClass): #Inherits setdata
def display(self): #Changes display
print('Current value = "%s"' % self.data)
class ThirdClass(SecondClass):
def __init__(self, value): #__init__方法,也称为构造函数方法,用于初始化对象的状态
self.data = value
def __add__(self, other): #运算符重载,"+"表达式会触发"__add__"方法
return ThirdClass(self.data + other)
#对于print,Python把要打印的对象传递给__str__中的self,该方法返回的字符串看做是对象的打印字符串
def __str__(self):
return '[ThirdClass: %s]' % self.data
def mul(self, other): #in-place change: named
self.data *= other
测试结果:
一个简单完整的类
一个完整的例子(Encapsulation, Inheritance, Polymorphism)
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def getLastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay = int(self.pay * (1 + percent))
def __str__(self):
return '[Person: %s, %s]' % (self.name, self.pay)
class Manager(Person):
def __init__(self, name, pay): #Redefine constructor
Person.__init__(self, name, 'manager', pay)
def giveRaise(self, percent, bonus=.10): #Redefine at this level
Person.giveRaise(self, percent + bonus) #Call Person's version
def __str__(self):
return '[Manager: %s, %s]' % (self.name, self.pay)
if __name__ == '__main__':
p1 = Person('Michael Jordan')
p2 = Person('Kobe Bryant', job='developer', pay=100000)
print(p1)
print(p2)
print(p1.getLastName(), p2.getLastName())
p2.giveRaise(.10)
print(p2)
p3 = Manager("David Stern", 50000)
p3.giveRaise(.10)
print(p3.getLastName())
print(p3)
print('--All three--')
for object in (p1, p2, p3):
object.giveRaise(.10)
print(object)
测试结果: