1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python类方法 静态方法 全局变量的使用

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

时间:2021-08-11 22:15:45

相关推荐

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

一、全局变量

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

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=[]@classmethoddef addData(cls,a2):cls.a1.append(a2)@classmethoddef showData(cls):return cls.a1

文件二:test.py

#! /usr/bin/env python#coding=utf-8from globalData import * class MergeHost(object):def __init__(self, resource_list):self.resource_list = resource_listdef merge_host(self):allResource=[]allResource.append(self.resource_list[0])for dict in self.resource_list:#print len(l4)k=0for item in allResource:#print 'item'if dict['host'] != item['host']:k=k+1#continueelse:breakif k == len(allResource):allResource.append(dict)taskhost=[]for item in allResource:taskhost.append(item['host'])print '########previous########'print glo_resourceprint '########previous########'#1、全局变量赋值glo_resource.append(taskhost)#2、类方法和类中数据成员的使用Common.addData(taskhost)print "Common list: ",Common.a1print "Common list: ",Common.showData()return taskhostclass 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"@staticmethoddef Foo1():print("Call static method foo1()\n")@classmethoddef 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 taskhostm = 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 methodmethodstatic methodCall static method foo1()Call class method foo2()('cls.__name__ is ', 'A')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。