面向对象编程
1.类和对象
类与对象是面向编程的两个主要方面。一个类能够创建一种新的类型(Type),对象(Object)就是类的实例(Instance)。
- 字段(Field):属于类或对象的普通变量,用来存储数据
- 方法(Method):属于类的函数,用来实现某些功能
- 属性(Attribute):字段与方法统称为类的属性
字段有两种类型:
- 实例变量(Instance Variables)
- 类变量(Class Variables)
类方法与普通函数的区别:
- 类方法必须有一个额外的名字self,且必须添加到参数列表的开头。
2.创建类
2.1最简单的类
class Person:
pass # 一个空的代码块
p = Person()
print(p)
2.2创建方法
class Person:
def say_hi(self):
print('Hello, how are you?')
# 虽然say_hi这一方法不需要参数,但依旧在函数定义中拥有(self)变量
p = Person()
p.say_hi()
2.3__init__方法
__init__方法会在类的对象被实例化时立即运行。
class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Chardman')
p.say_hi()
2.4类变量与对象变量
字段(Field)有两种类型——类变量与对象变量:
- 类变量(Class Variables)是共享的,可以被属于该类的所有实例访问。
- 对象变量(Object Variables)由类的每一个独立的对象或实例所拥有。
# coding=UTF-8
class Robot:
"""表示有一个带有名字的机器人"""
# 一个类变量,用来计数机器人的数量
population = 0
def __init__(self, name):
"""初始化数据"""
self.name = name
print('(Initializing {})'.format(self.name))
# 当有人创建时,机器人的数量将会增加
Robot.population += 1
def die(self):
"""机器人挂了"""
print("{} is beging 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('Greeting, my masters call me {}.'.format(self.name))
@classmethod # 用装饰器将how_many方法标记为类方法
def how_many(cls):
print('We have {:d} robots'.format(cls.population))
driod1 = Robot('R2-D2')
driod1.say_hi()
Robot.how_many()
driod2 = Robot('C-P30')
driod2.say_hi()
Robot.how_many()
print('\nRobots can do some work here.\n')
print("Robots have finished their work. So let's destroy them" )
driod1.die()
driod2.die()
Robot.how_many()
- 注:当一个对象变量与一个类变量名称相同时,类变量将会被隐藏。
2.5继承
- 基类(Base Class)或超类(Superclass)
- 派生类(Derived Classes)或子类(Subclass)
# codeing=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(SchoolMenber):
'''代表一位老师。'''
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. Xin', 40, 30000)
s = Student('Chardman', 30, 100)
members = [t, s]
for member in members:
# 对全体师生工作
member.tell()