相关疑难解决方法(0)

3360
推荐指数
24
解决办法
73万
查看次数

Python中的类方法差异:绑定,未绑定和静态

以下类方法有什么区别?

是一个是静态而另一个不是?

class Test(object):
  def method_one(self):
    print "Called method_one"

  def method_two():
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two()
Run Code Online (Sandbox Code Playgroud)

python

233
推荐指数
4
解决办法
15万
查看次数

Python中有三种以上的方法吗?

据我所知,Python中至少有3种方法具有不同的第一个参数:

  1. 实例方法 - 实例,即 self
  2. class方法 - 类,即 cls
  3. 静态方法 - 没什么

这些经典方法在Test下面的类中实现,包括常用方法:

class Test():

    def __init__(self):
        pass

    def instance_mthd(self):
        print("Instance method.")

    @classmethod
    def class_mthd(cls):
        print("Class method.")

    @staticmethod
    def static_mthd():
        print("Static method.")

    def unknown_mthd():
        # No decoration --> instance method, but
        # No self (or cls) --> static method, so ... (?)
        print("Unknown method.")
Run Code Online (Sandbox Code Playgroud)

在Python 3中,unknown_mthd可以安全地调用它,但它在Python 2中引发了一个错误:

>>> t = Test()

>>> # Python 3
>>> t.instance_mthd()
>>> Test.class_mthd()
>>> t.static_mthd()
>>> Test.unknown_mthd()

Instance method.
Class …
Run Code Online (Sandbox Code Playgroud)

python methods

5
推荐指数
1
解决办法
143
查看次数

标签 统计

python ×3

methods ×2

oop ×1

python-decorators ×1