下面定义的代码Duck类由以下组合而成Bill类和Tail班级。我的问题是至于方法about() inside Duck类定义,为什么可以写bill.description
and tail.length
? Is self
这里省略了?如果是,我什么时候可以省略self
?我可以把它们省略在里面吗__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()
The output are as follows,
长话短说:你MUST use self.
每当您想要访问当前实例的属性(数据属性、属性或方法)时。
对于更详细的答案:当使用def
in a class
声明,你创建的不是一个“方法”,而是一个普通的函数。当查找类或实例属性时(Duck.about
or duck.about
)这个函数将被包装(连同它所查找的类和实例)在一个可调用的函数中method
对象将负责自动将实例(或类)对象作为第一个参数注入到函数调用中。您可以在这里阅读全部详细信息:https://wiki.python.org/moin/FromFunctionToMethod https://wiki.python.org/moin/FromFunctionToMethod
正如其他人已经提到的,您的代码片段只是意外地“起作用”,因为它最终会查找恰好已定义的全局名称,并且一旦未定义这些名称就会中断:
# tail = Tail('long')
# bill = Bill('wide orange')
duck = Duck(Bill('wide orange'), Tail('long'))
duck.about()
=> 崩溃NameError
如果重新绑定这些全局名称,您还会得到意想不到的结果,即:
tail = Tail('long')
bill = Bill('wide orange')
duck1 = Duck(bill, tail)
tail = Tail('short')
bill = Bill('norvegian blue')
duck2 = Duck(bill, tail)
duck1.about()
=> 呃,为什么它打印“短挪威蓝”???
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)