Person
class Person:
def __init__(self,name):
self.name = name
def sayHi(self):
print('Hello! My Name is',self.name)
p = Person('Roy')
p.sayHi()
Robot
class Robot:
population = 0
def __init__(self,name):
self.name = name
print('Initaializeing {}'.format(self.name))
Robot.population += 1
def die(self):
print('{} is destoryed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{} was the last one'.format(self.name))
else:
print('there are still {} robots working'.format(Robot.population))
def sayHi(self):
print('Greetings,my master call me',self.name)
@classmethod
def howManay(cls):
print('we have {} robots'.format(Robot.population))
roy = Robot('roy')
roy.sayHi()
Robot.howManay()
lily = Robot('lily')
lily.sayHi()
lily.howManay()
lily.die()
Robot.howManay()
roy.die()
Robot.howManay()
继承
class SchoolMember:
def __init__(self,name,age):
self.name = name
self.age = age
print('Initialized SchoolMember',self.name)
def tell(self):
print('name:',self.name,'age:',self.age)
class Teacher(SchoolMember):
def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary = salary
print('Initilialized Teacher',self.name)
def tell(self):
SchoolMember.tell(self)
print('salary:',self.salary)
class Student(SchoolMember):
def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks = marks
print('Initialized Student',self.name)
def tell(self):
SchoolMember.tell(self)
print('Marks',self.marks)
t = Teacher('Roy',40,3000)
s = Student('Lily',18,99)
t.tell()
s.tell()
网友评论