Through the script case, the application of several concepts of class in Python in the script is analyzed.
The script is as follows:
++++++++++++++++++++++++++++++++++++++++
#!/usr/bin/env python
#-*-Coding:utf8-*-
class MyClass (object): #定义类
message = "Hello, Developer" #定义类的成员变量
def Show (self): #类中的成员函数, must take parameter self
Print Self.message
print "Here's%s in%s!" % (Self.name,self.color)
@staticmethod #定义静态函数装饰器
def printmessage (): #定义静态函数, can be called directly through the class name
print "Printmessage is called"
Print Myclass.message
@classmethod #定义类函数装饰器
def createobj (CLS, name, color): #定义类函数, can be called directly through the class name; The first argument must be: the implicit argument, the alternative class name itself
print "Object would 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 # Defines instance member variables
Self.color = Color
def __del__ (self): #定义析构函数: Inverse function of constructors
print "destructor is called for%s!"% self.name
#通过类名来访问: Static Functions and Class functions
myclass.printmessage ()
Inst = myclass.createobj ("Toby", "Red")
Print Inst.message
del Inst
Output Result:
Printmessage is called
Hello, Developer.
Object would be Created:myclass (Toby, Red)
Constructor is called with Params:toby Red
Hello, Developer.
destructor is called for toby!
++++++++++++++++++++++++++++++++++++++++++++++++++
Reference: Python high-efficiency development combat
"Python"-"class parsing"--"script instance"