Can python have class or instance methods that do not have “self” as the first argument? [duplicate]

时间秒杀一切 提交于 2020-01-13 04:35:06

问题


Possible Duplicate:
Why do you need explicitly have the “self” argument into a Python method?
Python ‘self’ explained

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.


回答1:


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)

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)    



回答2:


static methods don't need self, they operate on the class

see a good explanation of static here: Static class variables in Python



来源:https://stackoverflow.com/questions/14327794/can-python-have-class-or-instance-methods-that-do-not-have-self-as-the-first-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!