十. 面向对象编程
Python中所有事物皆对象。没有类似Java中的基本数据类型,Python中整型数是int类对象。
类(对象)拥有的变量称为域(fields), 类(对象)拥有的函数称为方法(methods)。域和方法都是类的属性(attributes)。
类通过关键字class定义,类的域和方法在class声明后的块中定义。如:
class Person:
pass # An empty block
p = Person()
前两行定义类Person,第三行创建Person类对象p。
实例方法(对象方法)
Python中对象方法中拥有一个(必须有一个)特殊参数self(也可以是其他名称),位于对象方法的参数列表中首位,调用时不需要给它赋值,Python会自动将当前对象引用赋给给参数,相当Java中的this。如:
class Person:
def sayHi(self):
print('Hello, how are you')
p = Person()
p.sayHi()
上面定义了类Person,它拥有sayHi方法,它拥有一个必需参数self,调用时直接调用sayHi(),无需给self传参。
初始化方法__init__
初始化方法在类对象实例化时调用,方法名固定为__init__。
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
print('Person对象初始化')
p = Person('Swaroop')
>python class_init.py
Person对象初始化
类和对象变量
Python有两种变量:类变量和实例变量。类变量属于类,被类的所有对象共享;实例变量属于类对象,每个类对象都有自己的变量,与其他类对象无关。类变量通过类名.变量名来访问,实例变量通过对象.变量名来访问,在类方法中通过self.变量名类访问。如:
#!/usr/bin/python
# Filename: objvar.py
class Robot:
'''Represents a robot, with a name.'''
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
'''Initializes the data.'''
self.name = name
print('(Initializing {0})'.format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''
print('Greetings, my masters call me {0}.'.format(self.name))
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
上面程序中population为类变量,name为对象变量,population通过类名来访问Robot.population,对象变量在方法中通过self来访问self.name。
销毁方法__del__
__del__方法为对象销毁方法,在对象彻底不再使用时执行,但执行时间不能确定,除非明确执行对象删除方法(del obj),此时会立即调用__del__方法,如上例所示。
静态方法
上例中howMany方法为静态方法,可以直接通过类名来访问Robot.howMany(),也可以通过类对象来访问。定义时不需要self参数。静态方法的定义,注意这句话howMany = staticmethod(howMany),它将howMany方法转换为静态方法。详细信息查看help(staticmethod)
类方法
类方法与对象方法类似,也有一个必须的参数cls(可以为其他名称),调用时Python自动将类传递给参数cls。类方法也可以直接通过类名来方法。如:
>>>class Person:
def sayHello(cls):
print(cls, 'say Hello')
>>>Person.sayHello()
<class '__main__.Person'> say Hello
Python中类私有变量和私有方法以两个下划线(__)开头,其他变量均为公共变量,方法均为虚方法(可以被子类覆盖)。
继承
Python中一个类可以继承多个类,也具有多态性。子类构造函数不会自动调用父类构造函数,如果要调用父类构造函数,必须明确调用。如
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {0})'.format(self.name))
def tell(self):
'''Tell my details.'''
print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end="
")
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{0:d}"'.format(self.salary))
类Teacher继承类SchoolMember,定义时父类写在子类名后括号中,可以有多个父类,多个父类用逗号分隔
Python中所有事物皆对象。没有类似Java中的基本数据类型,Python中整型数是int类对象。
类(对象)拥有的变量称为域(fields), 类(对象)拥有的函数称为方法(methods)。域和方法都是类的属性(attributes)。
类通过关键字class定义,类的域和方法在class声明后的块中定义。如:
class Person:
pass # An empty block
p = Person()
前两行定义类Person,第三行创建Person类对象p。
实例方法(对象方法)
Python中对象方法中拥有一个(必须有一个)特殊参数self(也可以是其他名称),位于对象方法的参数列表中首位,调用时不需要给它赋值,Python会自动将当前对象引用赋给给参数,相当Java中的this。如:
class Person:
def sayHi(self):
print('Hello, how are you')
p = Person()
p.sayHi()
上面定义了类Person,它拥有sayHi方法,它拥有一个必需参数self,调用时直接调用sayHi(),无需给self传参。
初始化方法__init__
初始化方法在类对象实例化时调用,方法名固定为__init__。
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
print('Person对象初始化')
p = Person('Swaroop')
>python class_init.py
Person对象初始化
类和对象变量
Python有两种变量:类变量和实例变量。类变量属于类,被类的所有对象共享;实例变量属于类对象,每个类对象都有自己的变量,与其他类对象无关。类变量通过类名.变量名来访问,实例变量通过对象.变量名来访问,在类方法中通过self.变量名类访问。如:
#!/usr/bin/python
# Filename: objvar.py
class Robot:
'''Represents a robot, with a name.'''
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
'''Initializes the data.'''
self.name = name
print('(Initializing {0})'.format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''
print('Greetings, my masters call me {0}.'.format(self.name))
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
上面程序中population为类变量,name为对象变量,population通过类名来访问Robot.population,对象变量在方法中通过self来访问self.name。
销毁方法__del__
__del__方法为对象销毁方法,在对象彻底不再使用时执行,但执行时间不能确定,除非明确执行对象删除方法(del obj),此时会立即调用__del__方法,如上例所示。
静态方法
上例中howMany方法为静态方法,可以直接通过类名来访问Robot.howMany(),也可以通过类对象来访问。定义时不需要self参数。静态方法的定义,注意这句话howMany = staticmethod(howMany),它将howMany方法转换为静态方法。详细信息查看help(staticmethod)
类方法
类方法与对象方法类似,也有一个必须的参数cls(可以为其他名称),调用时Python自动将类传递给参数cls。类方法也可以直接通过类名来方法。如:
>>>class Person:
def sayHello(cls):
print(cls, 'say Hello')
>>>Person.sayHello()
<class '__main__.Person'> say Hello
Python中类私有变量和私有方法以两个下划线(__)开头,其他变量均为公共变量,方法均为虚方法(可以被子类覆盖)。
继承
Python中一个类可以继承多个类,也具有多态性。子类构造函数不会自动调用父类构造函数,如果要调用父类构造函数,必须明确调用。如
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {0})'.format(self.name))
def tell(self):
'''Tell my details.'''
print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end="
")
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{0:d}"'.format(self.salary))
类Teacher继承类SchoolMember,定义时父类写在子类名后括号中,可以有多个父类,多个父类用逗号分隔