首页 > 代码库 > python 静态方法、实例方法、类方法

python 静态方法、实例方法、类方法

实例方法:

class A:
    data = http://www.mamicode.com/0>

type(A) #out:type

A.__dict__ #out:技术分享

a = A() #out:{}

类方法:@classmethod

class A:
    data = 0
    def printd(self):
        print(self.data)
def getdata():
     A.data = 1
     print(A.data)
   
     
class A:
    data = 0
    def printd(self):
        print(self.data)

    def getdata():
        A.data = 1
        print(A.data)
   

a = A()

a.getdata() #out:技术分享

目的:写一个跟类交互,不跟实例交互的方法

class A:
    data = 0
    def printd(self):
        print(self.data)

    @classmethod
    def getdata(cls):
        cls.data = 1
        print(cls.data)
   

 

 技术分享

 

静态方法:

IND = NO
def checkind():
    return IND == NO
        
class Kls:
    def  __init__(self,data):
        self.data = data
    
    def do_reset(self):
        if checkind():
            print(set done for,self.data)                      
    def set_db(self):
        if checkind():
             self.db = new db connection
             print(DB connection made for:,self.data)
IND = NO

        
class Kls:
    def  __init__(self,data):
        self.data = data
        
    def checkind():
        return IND == NO

    def do_reset(self):
        if checkind():
            print(set done for,self.data)        
              
    def set_db(self):
        if checkind():
             self.db = new db connection
             print(DB connection made for:,self.data)
IND = NO

        
class Kls:
    def  __init__(self,data):
        self.data = data
    @staticmethod    
    def checkind():
        return IND == NO

    def do_reset(self):
        if checkind():
            print(set done for,self.data)        
              
    def set_db(self):
        if checkind():
             self.db = new db connection
             print(DB connection made for:,self.data)

  技术分享

TODO:调用静态方法加self与不加self

python 静态方法、实例方法、类方法