加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中定义一个引用self而不称为“self”的类方法是否有用?

发布时间:2020-12-20 13:01:53 所属栏目:Python 来源:网络整理
导读:我正在教自己 Python,我在 Dive into Python section 5.3中看到以下内容: By convention,the first argument of any Python class method (the reference to the current instance) is called self . This argument fills the role of the reserved word th
我正在教自己 Python,我在 Dive into Python section 5.3中看到以下内容:

By convention,the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java,but self is not a reserved word in Python,merely a naming convention. Nonetheless,please don’t call it anything but self; this is a very strong convention.

考虑到self不是Python关键字,我猜测使用其他东西有时会很有用.有这种情况吗?如果没有,为什么它不是关键字?

解决方法

我见过的唯一一个例子就是在类定义之外定义一个函数,然后将它赋给类,例如:

class Foo(object):
    def bar(self):
        # Do something with 'self'

def baz(inst):
    return inst.bar()

Foo.baz = baz

在这种情况下,self使用起来有点奇怪,因为该函数可以应用于许多类.我经常看到使用inst或cls代替.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读