"Python"-"class parsing"--"script instance"

Source: Internet
Author: User

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.