实例1
- class Person:
- # 相当于构造函数
- def __init__(self, name):
- self.name = name
- def say_hello(self):
- print('Hello, how are you today?', self.name)
- # 创建对象并调用对象的方法
- p = Person('haha')
- p.say_hello()
- # 创建一个匿名对象并且调用它自己的方法
- Person('Xiuxiu').say_hello()
复制代码 实例2
- # coding = UTF-8
- class Robot:
- """
- 表示一个带有名字的机器人
- """
- # 定义一个类变量,用于统计机器人的数量
- population = 0
- def __init__(self, name):
- """初始化数据"""
- self.name = name
- print('(Initializing{})'.format(self.name))
- # 对象创建以后数量就增加1
- Robot.population += 1;
- def die(self):
- """对象挂了"""
- print("{} is being destroyed!".format(self.name))
- Robot.population -= 1
- if Robot.population == 0:
- print('{} was the last one '.format(self.name))
- else:
- print('There are still {:d} robots working '.format(Robot.population))
- def say_hi(self):
- """机器人的问候"""
- print('Welcome'.format(self.name))
- # 这是一个类方法,可以不用实例化就可以直接调用这个方法(相当于是一个静态方法)
- @classmethod
- def how_many(cls):
- """打印出当前的人口数量"""
- print('We have {:d} robots'.format(cls.population))
- droid1 = Robot("R2-D2")
- droid1.say_hi()
- Robot.how_many()
- droid2 = Robot("C-3PO")
- droid2.say_hi()
- Robot.how_many()
- print("\nRobots can do some work here.\n")
- print("Robots have finished their work. So let's destroy them.")
- droid1.die()
- droid2.die()
- Robot.how_many()
- # 输出文档字符串
- print(droid1.__doc__)
复制代码 实例3:对继承的理解
- # coding = UTF-8
- class SchoolMember:
- '''代表任何学校里的成员。'''
- def __init__(self, name, age):
- self.name = name
- self.age = age
- print('(Initialized SchoolMember: {})'.format(self.name))
- def tell(self):
- '''告诉我有关我的细节。'''
- print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
- class Teacher(SchoolMember):
- '''代表一位老师。'''
- def __init__(self, name, age, salary):
- # 开始实现继承
- SchoolMember.__init__(self, name, age)
- self.salary = salary
- print('(Initialized Teacher: {})'.format(self.name))
- def tell(self):
- # 调用父类的函数
- SchoolMember.tell(self)
- print('Salary: "{:d}"'.format(self.salary))
- class Student(SchoolMember):
- '''代表一位学生。'''
- def __init__(self, name, age, marks):
- # 开始实现继承
- SchoolMember.__init__(self, name, age)
- self.marks = marks
- print('(Initialized Student: {})'.format(self.name))
- def tell(self):
- # 调用父类的函数
- SchoolMember.tell(self)
- print('Marks: "{:d}"'.format(self.marks))
- t = Teacher('Mrs. Shrividya', 40, 30000)
- s = Student('Swaroop', 25, 75)
- # 打印一行空白行
- print()
- members = [t, s]
- for member in members:
- # 对全体师生工作
- member.tell()
复制代码
|