Python普通方法、静态方法、类方法的区别

区别

 开始:创建类和方法

# -*-coding:utf-8-*-
# 普通方法,类方法,静态方法的区别
from xxx import other
__metaclass__ = type


class Tst:
    name = 'tst' 
    data = 'this is data'
    other = other # 通过 import 引入变量,供cls调用
    
    def __init__(self, sex):# @classmethod 方法不可以调用sex属性
        self.sex = sex

    # 普通方法
    def normal_method(self, name):
        print(self.data, name)

    # 类方法,可以访问类属性
    @classmethod
    def class_method(cls, name):
        print(cls.data, name)

    # 静态方法,不可以访问类属性,不带cls或者self
    @staticmethod
    def static_method(name):
        print(name)

测试

tst = Tst()
tst.data = 'this is new'
tst.normal_method('name')
tst.class_method('name')
tst.static_method('name')

结果如下:

  • 三种方法都可以通过实例来调用,但是类方法和静态方法无法访问实例属性,所以更改了tst.data仅对普通方法起了作用

In [1]: 
this is new name
this is data name
name

区别

  • 普通方法只能通过实例调用,不能通过类名调用;
  • 静态方法和类方法是可以通过类名直接调用

# error普通方法必须通过实例调用
Tst.normal_method('name')

#结果:

Tst.normal_method('name')
Traceback (most recent call last):

  File "<ipython-input-6-1f90993a8191>", line 1, in <module>
    Tst.normalMethod('name')

TypeError: normal_method() missing 1 required positional argument: 'name'
Tst.class_method('name')
Tst.static_method('name')

#结果
this is data name
name

总结

  • 普通方法,可以通过self访问实例属性
def normal_method(self,data) #带 self 的普通方法
  • 类方法,可以通过cls访问类属性 
@classmethod
def class_method(cls,data) #带 cls 的类方法
  • 静态方法,不可以访问,通过传值的方式
@staticmethod
def static_method(data)#只带 类属性 的静态方法

类Class __init__ 和 @classmethod 

这里要明确一个点:self指向的是类的实例,而不是类本身,如果想要在类里写一个函数(或者说方法),这个方法只和类本身交互,而不和类的实例交互,就可以使用@classmethod,比如向下面的例子:

class Kls(object):
    no_inst = 0
    def __init__(self):
        Kls.no_inst = Kls.no_inst + 1
    @classmethod
    def get_no_of_instance(cls_obj):
        return cls_obj.no_inst
ik1 = Kls()
ik2 = Kls()
print(ik1.get_no_of_instance())
print(Kls.get_no_of_instance())

输出为

2
2

 注意:一个包含 @classmethod 的类中,要不要有 __init__(self, 参数1)方法?

        1)可以有,这种情况下, @classmethod 方法是不需要参数1的,这样调用的时候可以不用实例化,这才是  @classmethod 方法的意义;

        2)如果类中方法全是  @classmethod 方法,这种情况不能有 __init__(self, 参数1)出现。

链接1链接2

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值