类方法与静态方法

来源:互联网 发布:手机怎么开通4g网络 编辑:程序博客网 时间:2024/06/10 04:32

方法

方法是通过 def 申明创造的函数
方法的工作方式与简单的函数一样。但是有种例外的情况:方法的第一个参数接受的是实例对象。

1, 实例方法:

def f(self, *arg)

2, 类方法:使用类属性

@classmethoddef cf(cls, *arg)

3,静态方法:不包含任何有关类的信息

@staticmethoddef sf(*arg)

对于实例方法的工作原理类似类方法。实际上,python自动映射实例方法调用到类方法。即:

instance.method(args,...)

将自动转换为类方法的调用:

class.method(instance, args,...)
class A(object):    def method(self, num)        print(num)a = A()a.method(4)# 4A.method(a, 4)# 4

类方法与实例方法

假设有如下类以及实例方法:

class A(object):    message = "class message"    @classmethod    def cf(cls):        print(cls.message)    def f(self, msg):        self.message = msg        print(self.message)    def __str__(self):        return self.message

由于f()是实例方法,通过实例来调用;

a = A()a.f("instance call")# instance call

a调用f()时,python将自动替换self为实例对象 a 。

对于类方法,直接通过类名来调用:

A.cf()# class message

message 是类的属性。

1, 绑定方法:
实例方法:上面定义的类中的 f()
类方法:上面定义的类中的 cf()

```a.f# <bound method A.f of <__main__.A object at 0x1066de7b8>>A.cf# <bound method A.cf of <class '__main__.A'>>a.cf# <bound method A.cf of <class '__main__.A'>>```

2, 非绑定方法:对于类调用:

```A.f# <function A.f at 0x106850400>```

静态方法

常见静态方法的定义为:

class B(object):    @staticmethod    def foo():        pass

以上定义与以下等同:

class B(object):    def foo():        pass    foo = staticmethod(foo)

假设有一个典型的实例计数程序:

class count(object):    nInstances = 0     def __init__(self):        count.nInstances = count.nInstances + 1    @staticmethod    def mun_instances():        print("number of instances :", count.nInstances)a = count()b = count()c =count()#实例化在不断修改类的属性。count.mun_instances()#类调用#number of instances : 3a.mun_instances()#实例调用#number of instances : 3   a.num_instances#<function count.num_instances at 0x106850598># 即静态类也是非绑定方法,函数

参考文章

CLASS METHOD VS STATIC METHOD 2016

http://www.bogotobogo.com/python/python_differences_between_static_method_and_class_method_instance_method.php

0 0