python笔记-类方法、静态方法和实例方法

1.静态方法

静态方法是指类中不需要通过实例对象(即,这类函数的第一个位置参数不是self)来调用就可以使用的方法。需要注意的是,不这类方法不需要通过实例对象来调用,但类的实例对象也是可以调用这类函数的。在python3中使用装饰器@staticmethod来声明静态方法。

​class Static_Test_A:
    @staticmethod
    def fun_a(arg):
        print(arg)

if __name__=='__main__':
    Static_Test_A.fun_a('hello world')
    ca=Static_Test_A()
    ca.fun_a('hello,this is a new world')

其运行结果为:

hello world
hello,this is a new world

2.实例方法

实例方法必须通过类的实例对象来调用,所以这个函数的第一个位置参数必须是self。当使用类的实例对象来调用这类函数时,该实例对象会自动地赋值给self参数。除此之外,也可以显示地通过将实例对象作为第一个位置参数传入到实例方法中来调用该方法。

class Static_Test_A:
    def fun_a(self,arg):
        print(arg)

if __name__=='__main__':
    ca=Static_Test_A()
    ca.fun_a('hello world')
    ca_1=Static_Test_A()
    Static_Test_A.fun_a(ca,'hello, this is a new world')

其代码运行结果如下:

hello world
hello, this is a new world

3.类方法

类方法,顾名思义就是类对象所拥有的方法。其定义时,除了使用@classmethod装饰之外,该方法的第一个位置参数默认为cls。类方法既可以通过实例对象来引用,也可以通过类对象来引用。

class People:
    @classmethod
    def getCountry(cls,value):
        return(value+'new')

p=People()
p.getCountry('hello ')
People.getCountry('world ')

其代码运行结果为:

hello new
world new

另外,类方法可以对类对象的属性进行修改:

class People:
    country='china'
    @classmethod
    def setCountry_2(cls,value):
        cls.country=value
print(People.country)
People.setCountry_2('japan')
print(People.country)

代码运行结果为:

china
japan

而静态方法无法对类的属性进行修改的。

class People:
    country='china'
    @staticmethod
    def setCountry_1(value):
        print("code is running")
        country=value
print(People.country)
People.setCountry_1('japan')
print(People.country)

其代码运行结果为:

china
code is running
china

实例方法也无法对类的属性进行修改:

class People:
    country='china'
    def setCountry_3(self,value):
        self.country=value
p=People()
print(People.country)
p.setCountry_3('japan')
print('类属性country:'+People.country)
print('实例属性country:'+p.country)

代码运行结果为:

china
类属性country:china
实例属性country:japan

猜你喜欢

转载自blog.csdn.net/yeshang_lady/article/details/82429731