python - 在python中,什么时候可以省略self?

标签 python class

下面的代码将 Duck 类定义为 Bill 类和 Tail 类的组合。我的问题是,对于Duck 类定义中的about() 方法,为什么可以写bill.descriptiontail。长度?这里省略了self吗?如果是,我什么时候可以省略 self?我可以在 __init__ 方法中省略它们吗?

class Bill(): 
    def __init__(self, description):
        self.description = description 
class Tail(): 
    def __init__(self, length): 
        self.length = length 
class Duck(): 
    def __init__(self, bill, tail): 
        self.bill = bill
        self.tail = tail 
    def about(self): 
        print('This duck has a', bill.description, 'bill and a', tail.length, 'tail')
tail = Tail('long')
bill = Bill('wide orange') 
duck = Duck(bill, tail)
duck.about()

输出如下, enter image description here

最佳答案

长话短说:只要您想访问当前实例的属性(数据属性、特性或方法),您必须使用self.

更详细的答案:在 class 语句中使用 def 时,您创建的不是“方法”,而是普通函数。当查找类或实例属性(Duck.aboutduck.about)时,此函数将被包装(与查找它的类和实例一起)在一个可调用的 method 对象,它将自动将实例(或类)对象作为函数调用的第一个参数注入(inject)。您可以在此处阅读全部详细信息:https://wiki.python.org/moin/FromFunctionToMethod

正如其他人已经提到的,您的代码片段只是意外地“起作用”,因为它最终会查找恰好已定义的全局名称,并在这些名称未定义时立即中断:

# tail = Tail('long')
# bill = Bill('wide orange') 
duck = Duck(Bill('wide orange'), Tail('long'))
duck.about()

=> 崩溃并出现 NameError

如果重新绑定(bind)这些全局名称,您还会得到意想不到的结果,即:

tail = Tail('long')
bill = Bill('wide orange') 
duck1 = Duck(bill, tail)

tail = Tail('short')
bill = Bill('norvegian blue') 
duck2 = Duck(bill, tail)

duck1.about()

=> 呃,为什么它会打印“short norvegian blue”???

关于python - 在python中,什么时候可以省略self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963018/

相关文章:

python - 如何在Python中复制或删除有条件的行

python - 我如何从 y_true 和 y_pred 得到真正的底片?

python - 如何在python中指定时间戳的格式

c++ - 如何在使用此数组初始化对象时知道数组的大小?

java - 引用接口(interface)创建对象

python - 拆分十六进制的最佳方法?

python - Airflow :如何强制失败 bash 运算符

c++ - 使用字符串和整数逐行读取文件

python - 如何建立具有相互依赖关系的Python类集合?

c++ - 运算符重载错误: no match for 'operator>>'