面向对象编程
一. 例子一:构造函数,析构函数,类成员变量,实例成员变量
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class MyClass(object):
#这里的message是类成员变量,也就是MyClass类和所有MyClass对象共享该成员变量
message = 'Hello, Developer'
def show(self):
print self.message
print "Here is %s in %s!" %(self.name, self.color)
#构造函数
def __init__(self, name="unset", color='black'):
print "Constructor is called with params: ",name," ",color
#这里的self.name和self.color是实例成员变量
self.name = name
self.color = color
#析构函数
def __del__(self):
print "Destructor is called for %s!" %self.name
if __name__ == "__main__":
inst2 = MyClass("David")
inst2.show()
print "Color of inst2 is ",inst2.color, "\n"
inst3 = MyClass('Lisa','yellow')
inst3.show()
print "Name of inst3 is ",inst3.name,"\n"
#析构函数,可以显式调用。否则,程序会自动调用
del inst2, inst3
运行结果
Constructor is called with params: David black
Hello, Developer
Here is David in black!
Color of inst2 is black
Constructor is called with params: Lisa yellow
Hello, Developer
Here is Lisa in yellow!
Name of inst3 is Lisa
Destructor is called for David!
Destructor is called for Lisa!
二. 静态函数和类函数
到目前为止,绝大多数的“类成员变量”,均与实例绑定,即只能通过对象访问,而不可以通过类名访问。
而事实上,Python中,支持两种基于类名访问成员的函数:“静态函数”和“类函数”
不同点在于,类函数有一个隐形参数cls用来获取类信息,而静态函数没有该参数。
静态函数使用装饰器@staticmethod定义
类函数使用装饰器@classmethod定义
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class MyClass(object):
message = 'hello,Developer'
def show(self):
print self.message
print "Here is %s in %s!" %(self.name, self.color)
@staticmethod
def printMessage():
print "printMessage is called"
print MyClass.message
@classmethod
def createObj(cls,name,color):
print "Object will be created: %s(%s.%s)" %(cls.__name__,name,color)
return cls(name,color)
def __init__(self,name='unset',color="black"):
print "Constructor is called with params: ",name," ",color
self.name =name
self.color =color
def __del__(self):
print "Destrcutor is called %s! "%self.name
MyClass.printMessage()
inst = MyClass.createObj("Toby", "Red")
print inst.message
del inst
运行结果
printMessage is called
hello,Developer
Object will be created: MyClass(Toby.Red)
Constructor is called with params: Toby Red
hello,Developer
Destrcutor is called Toby!