Python 中的类方法差异:绑定、未绑定和静态 [英] Class method differences in Python: bound, unbound and static
问题描述
以下类方法有什么区别?
一个是静态的,另一个不是吗?
类测试(对象):def method_one(self):打印调用的method_one"def method_two():打印调用的method_two"a_test = 测试()a_test.method_one()a_test.method_two()
在 Python 中,bound 和 unbound 方法是有区别的.
基本上,调用成员函数(如method_one
),绑定函数
a_test.method_one()
被翻译成
Test.method_one(a_test)
即对未绑定方法的调用.因此,调用您的 method_two
版本将失败并返回 TypeError
您可以使用装饰器更改方法的行为
类测试(对象):def method_one(self):打印调用的method_one"@静态方法def method_two():打印调用的方法二"
装饰器告诉内置的默认元类 type
(类的类,参见 this question) 不为 method_two
创建绑定方法.
现在,您可以直接在实例或类上调用静态方法:
<预><代码>>>>a_test = 测试()>>>a_test.method_one()调用method_one>>>a_test.method_two()调用方法二>>>Test.method_two()调用方法二What is the difference between the following class methods?
Is it that one is static and the other is not?
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()
In Python, there is a distinction between bound and unbound methods.
Basically, a call to a member function (like method_one
), a bound function
a_test.method_one()
is translated to
Test.method_one(a_test)
i.e. a call to an unbound method. Because of that, a call to your version of method_two
will fail with a TypeError
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
You can change the behavior of a method using a decorator
class Test(object):
def method_one(self):
print "Called method_one"
@staticmethod
def method_two():
print "Called method two"
The decorator tells the built-in default metaclass type
(the class of a class, cf. this question) to not create bound methods for method_two
.
Now, you can invoke static method both on an instance or on the class directly:
>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two
这篇关于Python 中的类方法差异:绑定、未绑定和静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!