内部类
所谓内部类就是在类的内部定义的类,主要目的是为了更好的抽象现实世界。
比如,汽车是个类,汽车的底盘、轮胎也可以抽象为类,将其定义到汽车类中则形成内部类,更好的描述汽车类,因为底盘、轮胎都是汽车的一部分。
内部类的实例化
方法1:直接使用外部类调用内部类
object_name = outclass_name.inclass_name()
采用外部类.内部类来实例化
方法2:先对外部类进行实例化,然后再实例化内部类
out_name = outclass_name() #实例化外部类
in_name = out_name.inclass_name() #实例化内部类
in_name.method() #调用内部类的方法
outclass_name.inclass_name.variable #直接调用内部属性
类的内置方法
类的内置方法也叫做魔术方法
内置方法为以__开头,以__结尾的方法
str(self):用于类被实例化后,直接打印实例化对象时,显示的提示信息,不能用print,必须要用return
def __str__(self):
return "this is a str method"
构造函数和析构函数
- 构造函数:用于初始化类的内部状态,python提供的构造函数是__init__();这个函数是可选的,如果不提供,python默认会提供__init__函数。
class Car(object):
color = 'write'
def __init__(self,cl): #只在类实例化时才会执行,可以添加参数
#self.color = 'black'
self.color = cl #实例化时接收参数修改color属性值
self.run() #实例化时执行类的方法
def run(self):
print "Running..."
#audi = Car()
audi = Car('red') #实例化自动执行了run方法
print Car.color #输出为write
#print audi.color #输出为black
print audi.color #输出为red
- 析构函数:用于释放对象占用的资源,python提供的析构函数是__del__();这个函数也是可选的,如果不提供,python默认会提供析构函,在脚本最后执行。
def __del__(self):
print "this is del method"
垃圾回收机制
python采用垃圾回收机制来清理不再使用的对象,提供gc模块释放不再使用的对象。
python采用“引用计数”的算法方式来处理回收,即:当某个对象在其作用域内不再被其他对象引用时,python会自动清除对象。
gc模块的collect()方法可以一次性收集所有待处理的对象。
继承
继承是面向对象的重要特性之一。
继承是相对两个类而言的父子关系,子类继承父类的所有公有属性和方法。
继承实现了代码复用。
继承可以重用已经存在的数据和行为,减少代码的重复编写。Python在类名后使用一对括号来表示继承关系,括号中的类即为父类。
class MyClass(ParentClass)
如果父类定义了__init__方法,子类必须显式调用父类的__init__方法。
ParentClass.__init__(self,[args...])
如果子类需要扩展父类的行为,可以添加__init__方法的参数。
class Car(object): #新式类
#class Car: #旧式类
color = "write"
def __init__(self,pw):
print "init..."
self.power = pw
def run(self):
print "Car is running..."
class Wagon(Car):
def __init__(self):
# Car.__init__(self,200) #显式调用父类构造函数
super(Wagon, self).__init__(200) #使用super函数,作用同上,只能在新式类中使用
def run(self):
print "Wagon is running..."
audi = Wagon()
print audi.power
audi.run() #执行子类的方法
多重继承
Python支持多重继承,即一个类可以继承多个父类
class ClassName(Parent_c1, Parent_c2,...)
注意:当父类中出现多个自定义的__init__方法时,多重继承只执行第一个类的__init__方法,其他不执行。
class Car(object): #新式类
color = "write"
def __init__(self):
print "init..."
self.power = 200
def run(self):
print "%s Car is running..." % self.color
class Machine(object):
color = "green"
def __init__(self):
self.power = 150
def start(self):
print "Machine is starting, power is %s" % self.power
class Wagon(Car, Machine):
def __init__(self):
Machine.__init__(self) #指定执行的父类构造函数,默认执行第一个父类的构造函数
audi = Wagon()
audi.run() #run方法调用父类Car中的color属性,color默认为第一个父类Car的值
audi.start() #start方法调用父类Machine中的power属性,power属性在构造函数中,构造函数继承自Machine父类