python可以具有不具有"self"属性的类或实例方法吗?作为第一个论点? [英] Can python have class or instance methods that do not have "self" as the first argument?

查看:146
本文介绍了python可以具有不具有"self"属性的类或实例方法吗?作为第一个论点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么您需要明确拥有将"self"参数转换为Python方法?
解释了Python自我"

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.

推荐答案

如果您想要不需要访问self的方法,请使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆