python可以具有不具有"self"属性的类或实例方法吗?作为第一个论点? [英] Can python have class or instance methods that do not have "self" as the first argument?
问题描述
Possible Duplicate:
Why do you need explicitly have the "self" argument into a Python method?
Python ‘self’ explained
这只是出于我自己的目的.我正在学习python,并且已经使用python进入了OOP.我所见过的类中方法的每个示例都将"self"作为第一个参数.所有方法都是这样吗?如果是真的,是否不能编写python以便仅理解此参数,因此不需要此参数?谢谢.
This is just for my own edification. I am learning python and have moved into OOP with python. Every single example of a method in a class that I have seen has "self" as the first argument. Is this true of all methods? If it is true, couldn't python have been written so that this argument was just understood and therefore not needed? Thanks.
推荐答案
If you want a method that doesn't need to access self
, use 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
:
If you want access to the class, but not to the instance, use classmethod
:
class C(object):
@classmethod
def my_class_method(cls, foo, bar):
pass
c.my_class_method(1, 2)
这篇关于python可以具有不具有"self"属性的类或实例方法吗?作为第一个论点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!