在python中,何时可以省略self? [英] In python, when self can be omitted?
问题描述
下面的代码将 Duck 类定义为 Bill 类和 Tail 类的组合.我的问题是,关于 Duck 类定义中的 about()方法,为什么一个人可以写 bill.description
和 tail.长度
?这里是否省略了 self
?如果是,我什么时候可以省略 self
?我可以在 __ init __
方法中省略它们吗?
Codes below defined Duck class as composited from Bill class and Tail class. My questions is that as for the method about() inside Duck class definition, why can one write bill.description
and tail.length
? Is self
omitted here? If yes, when can I omit self
? Can I omit them inside __init__
method?
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()
输出如下,
推荐答案
长话短说:每当您要访问属性时,必须使用 self.
当前实例的(数据属性,属性或方法).
To make a long story short: you MUST use self.
whenever you want to access an attribute (data attribute, property or method) of the current instance.
一个更详细的答案:在 class
语句中使用 def
时,您创建的不是方法"而是简单的函数.当查询一个类或实例属性( duck.about
)时,此函数将被包装(连同在其上查找的类和实例一起)一个可调用的 method
对象,该对象将自动将实例(或类)对象作为函数调用的第一个参数注入.您可以在此处阅读全部详细信息: https://wiki.python.org/moin/FromFunctionToMethod
For a somewhat more detailed answer: when using def
in a class
statement, what you create is not a "method" but a plain function. When looked up a class or instance attribute (Duck.about
or duck.about
) this function will be wrapped (together with the class and instance on which it's looked up) in a callable method
object that will take care of automagically inject the instance (or class) object as first parameter to the function call. You can read the whole details here : https://wiki.python.org/moin/FromFunctionToMethod
正如其他已经提到的那样,您的代码段只是偶然地起作用",因为它最终看起来恰好是已定义的全局名称,并且在未定义这些名称时就中断了:
As other already mentionned, your code snippet only accidentally "works" because it ends up looking global names that happens to be defined, and breaks as soon as these names are not defined:
# tail = Tail('long')
# bill = Bill('wide orange')
duck = Duck(Bill('wide orange'), Tail('long'))
duck.about()
=>因 NameError
如果重新绑定这些全局名称,也将得到意想不到的结果,即:
You'd also get unexpected results if rebinding these global names ie:
tail = Tail('long')
bill = Bill('wide orange')
duck1 = Duck(bill, tail)
tail = Tail('short')
bill = Bill('norvegian blue')
duck2 = Duck(bill, tail)
duck1.about()
=> h,为什么会打印短的挪威蓝" ???
=> Duh, why does it prints "short norvegian blue" ???
这篇关于在python中,何时可以省略self?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!