<分区>
我在 Python 的 类 中看到的每个方法 示例都将 self
作为第一个参数。所有方法都是这样吗?如果是这样,难道不能编写 python 以便仅理解这个论点,因此不需要吗?
<分区>
我在 Python 的 类 中看到的每个方法 示例都将 self
作为第一个参数。所有方法都是这样吗?如果是这样,难道不能编写 python 以便仅理解这个论点,因此不需要吗?
最佳答案
如果你想要一个不需要访问self
的方法,使用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)
如果您想访问类,但不想访问实例,请使用classmethod
:
class C(object):
@classmethod
def my_class_method(cls, foo, bar):
pass
c.my_class_method(1, 2)
关于python - python 可以有没有 "self"作为第一个参数的类或实例方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327794/