您的位置:首页 > 编程语言 > Python开发

Python类方法、静态方法、全局变量的使用

2016-01-07 20:39 881 查看

一、全局变量

实现全局变量主要有两种方法:声明法和模块法

1、声明法

在文件开头声明全局变量variable,在具体函数中使用该变量时,需要事先声明 global variable,否则系统将该变量视为局部变量。

2、模块法(本文主要使用模块法)

把全局变量定义在一个单独的模块中,适用于不同文件之间的变量共享,而且一定程度上避免了全局变量的弊端。

二、类方法和静态方法

python没有和C++中static关键字,它的静态方法是怎样的?还有其它语言中少有的类方法又是怎么回事?

python中实现静态方法和类方法都是依赖于python的修饰器来实现的。

普通的对象方法、类方法和静态方法的区别如何?

对象方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数。

三、代码

文件一:globalData.py

#! /usr/bin/env python
#coding=utf-8

#1、把全局变量定义在一个单独的模块中:

glo_resource = []

#2、类方法的使用
class Common(object):
a1=[]

@classmethod
def addData(cls,a2):
cls.a1.append(a2)

@classmethod
def showData(cls):
return cls.a1


文件二:test.py

#! /usr/bin/env python
#coding=utf-8
from globalData import *

class MergeHost(object):

def __init__(self, resource_list):

self.resource_list = resource_list

def merge_host(self):

allResource=[]
allResource.append(self.resource_list[0])
for dict in self.resource_list:
#print len(l4)
k=0
for item in allResource:
#print 'item'
if dict['host'] != item['host']:
k=k+1
#continue
else:
break
if k == len(allResource):
allResource.append(dict)
taskhost=[]
for item in allResource:
taskhost.append(item['host'])

print '########previous########'
print glo_resource
print '########previous########'
#1、全局变量赋值
glo_resource.append(taskhost)
#2、类方法和类中数据成员的使用
Common.addData(taskhost)
print "Common list: ",Common.a1
print "Common list: ",Common.showData()
return taskhost

class MyClass():

def method(self):
print("method")

@staticmethod
def staticMethod():
print("static method")

@classmethod
def classMethod(cls):
print("class method")

class A(object):
"This ia A Class"
@staticmethod
def Foo1():
print("Call static method foo1()\n")

@classmethod
def Foo2(cls):
print("Call class method foo2()")
print("cls.__name__ is ",cls.__name__)

if __name__ == '__main__':

resource_list=[{'host':'compute21', 'cpu':2},{'host':'compute21', 'cpu':2},{'host':'compute22', 'cpu':2},
{'host':'compute23', 'cpu':2},{'host':'compute22', 'cpu':2},{'host':'compute23', 'cpu':2},
{'host':'compute24', 'cpu':2}]

hostSchedule = MergeHost(resource_list)
taskhost = hostSchedule.merge_host()

print 'glo_resource: ', glo_resource

#print 'taskhost: '
#print taskhost

m = MyClass()
m.classMethod()
m.method()
m.staticMethod()
A.Foo1();
A.Foo2();


运行test.py得到结果:

########previous########
[]
########previous########
Common list:  [['compute21', 'compute22', 'compute23', 'compute24']]
Common list:  [['compute21', 'compute22', 'compute23', 'compute24']]
glo_resource:  [['compute21', 'compute22', 'compute23', 'compute24']]
class method
method
static method
Call static method foo1()

Call class method foo2()
('cls.__name__ is ', 'A')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息