Python類方法 靜態方法 全域性變數的使用

2021-08-01 15:19:34 字數 3092 閱讀 7321

實現全域性變數主要有兩種方法:宣告法和模組法

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

defadddata

(cls,a2):

@classmethod

defshowdata

(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

defmerge_host

(self):

allresource=

for dict in self.resource_list:

#print len(l4)

k=0for item in allresource:

#print 'item'

if dict['host'] != item['host']:

k=k+1

#continue

else:

break

if k == len(allresource):

taskhost=

for item in allresource:

print

'########previous########'

print glo_resource

print

'########previous########'

#1、全域性變數賦值

#2、類方法和類中資料成員的使用

common.adddata(taskhost)

print

"common list: ",common.a1

print

"common list: ",common.showdata()

return taskhost

class

myclass

():def

method

(self):

print("method")

@staticmethod

defstaticmethod

():

print("static method")

@classmethod

defclassmethod

(cls):

print("class method")

class

a(object):

"this ia a class"

@staticmethod

deffoo1

(): print("call static method foo1()\n")

@classmethod

deffoo2

(cls):

print("call class method foo2()")

print("cls.__name__ is ",cls.__name__)

if __name__ == '__main__':

resource_list=[,,,

,,,]

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')

頂 0

Python 類方法 靜態方法

1 我們已經討論了類 物件可以擁有像函式一樣的方法,這些物件方法與函式的區別只是乙個額外的self變數 coding utf 8 usr bin python filename method.py class person grade 1 def init self,name self.name n...

Python 靜態方法 類方法

一 靜態方法 乙個不能訪問例項變數和類變數的方法,它與類唯一的關聯就是需要通過類名來呼叫這個方法。class person object def init self,name self.name name def eat self print s is eating self.name static...

python靜態方法 類方法

常規 1 class dog object 2def init self,name 3 self.name name45 defeat self 6print s is eating self.name 78 d1 dog lele 9 d1.eat 1.靜態方法 名義上由類管理,而實際在呼叫時,需...