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=[]

    @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')
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值