Python类与对象核心用法:从定义到继承详解
本文深入解析Python面向对象编程核心概念,涵盖类的定义语法、__init__构造函数与__del__析构函数的使用、类变量与对象变量的区别,以及通过SchoolMember、Teacher和Student示例演示继承机制。内容包含完整代码与输出分析,帮助开发者掌握Python类与对象的实际应用。
Python类与对象核心用法:从定义到继承详解
本文通过具体实例详细解析Python中类与对象的使用方法,供读者参考学习。
此前我们主要采用面向过程编程方式,本节将转向使用Python创建类和对象,即面向对象编程(OOP)。类和对象是OOP的两个核心要素:类用于定义新的类型,而对象则是该类的一个具体实例。这类似于整型变量int存储整数,该变量即为int类的实例(对象)。在Python中,类或实例中的变量被称为域(field),类或实例中的函数被称为方法(method),域和方法统称为类或实例的属性。
类的定义与空类示例
类的定义
在定义类或其内部函数时,若函数没有外部参数,必须将参数写为self。这样在外部调用时,可以明确区分调用的是哪个具体实例的函数。这里的self代表当前实例,其作用与C++中的this或Java中的this类似。
空类
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
p = Person()
print p
我们使用class语句后跟类名来创建一个新的类,随后是一个缩进的语句块作为类体。在示例中,我们使用了一个包含pass语句的空块,编译时会直接跳过该块,从而构成一个空类。
接下来,通过类名后跟一对圆括号来创建对象(或称为实例)。由于该类无需任何参数,因此在创建对象时也不需要传递参数。
$ python simplestclass.py <__main__.Person instance at 0xf6fcb18c>
打印该对象时,可以看到其所属的类名以及它在内存中的地址。
__init__构造函数与__del__析构函数
__init__函数
在上面的空类示例中,虽然没有显式定义任何内容,但Python仍会提供一个默认的构造函数。在Python中,类似构造函数的机制是__init__函数。当创建对象时,该函数会被自动调用。
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
输出:
$ python class_init.py Hello, my name is Swaroop
当新建一个Person对象时,由于__init__方法需要name参数,因此必须提供一个参数。可以看到该类拥有一个自己的域,在构造过程中,name的值被赋给对象内部的name属性。此外,可以看到sayHi方法虽然不需要外部参数,但在定义时仍需包含self参数。
__del__函数
与init方法类似,还存在一个特殊方法del,它在对象销毁时被调用,相当于析构函数。对象销毁意味着对象不再被使用,其占用的内存将返回给系统。然而,很难保证该方法具体在何时运行。如果希望明确指定其运行时机,可以使用del语句。相关代码示例将在后文展示。
类变量与对象变量的使用
使用类的变量
在Python中,所有的类成员(包括数据成员)默认都是公共的,所有的方法也都是有效的。
唯一的例外是:如果数据成员的名称以双下划线前缀开头(例如__privatevar),Python的名称修饰机制会将其视为私有变量。
因此,存在一种惯例:如果某个变量仅希望在类或对象内部使用,应使用单下划线前缀。其他名称则被视为公共的,可被其他类或对象访问。
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'There is nobody here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
输出:
$ python objvar.py (Initializing Swaroop) Hi, my name is Swaroop. I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. We have 2 persons here. Hi, my name is Swaroop. We have 2 persons here. Abdul Kalam says bye. There are still 1 people left. Swaroop says bye. There is nobody here.
这是一个较长的示例。其中,population属于Person类,因此是类变量;name变量属于对象(通过self赋值),因此是对象变量。
观察可知,init方法使用名字来初始化Person实例。在此方法中,我们将population加1,因为每创建一个实例就增加一个人。同时,self.name的值根据每个对象单独指定,这体现了其作为对象变量的特性。
请注意,你只能使用self变量来引用同一对象的变量和方法,这被称为属性引用。
当一个对象被清除时,del方法被调用,人数减1并输出谁离开了。起初Abdul Kalam被自动清除,随后Swaroop也被自动清除。清除顺序可能与对象闲置的时间有关,当闲置时间达到特定阈值时触发清除。
Python中的继承机制
继承
Python的继承机制与C++和Java没有显著差异,只需在构造函数及其他函数中记得添加self参数即可。函数的重载行为也与C++和Java一致。
示例:
#!/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: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
输出:
$ python inherit.py (Initialized SchoolMember: Mrs. Shrividya) (Initialized Teacher: Mrs. Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000" Name:"Swaroop" Age:"22" Marks: "75"
SchoolMember是父类,Student和Teacher是子类,继承的方法是在类定义中将参数设为SchoolMember。可以看到,当继承一个类时,首先调用的是父类的构造函数,然后才是子类的构造函数。
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









