我见过的每一个例子method in a class在Python中,有self
作为第一个参数。所有方法都是如此吗?如果是这样,难道Python不能被编写成让这个论点被理解并且因此不需要吗?
如果你想要一个不需要访问的方法self
, use staticmethod http://docs.python.org/2/library/functions.html#staticmethod:
class C(object):
def my_regular_method(self, foo, bar):
pass
@staticmethod
def my_static_method(foo, bar):
pass
c = C()
c.my_regular_method(1, 2)
c.my_static_method(1, 2)
如果您想访问class,但不是实例,使用classmethod http://docs.python.org/2/library/functions.html#classmethod:
class C(object):
@classmethod
def my_class_method(cls, foo, bar):
pass
c.my_class_method(1, 2)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)