我正在阅读Python编程文本,其中使用以下代码在游戏中创建场景:
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your Mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this.",
"You're worse than your Dad's jokes."
]
def enter(self):
print(Death.quips[randint(0, len(self.quips)-1)])
我的问题就在最后一行。使用特定的类名(在这种情况下Death.quips
与相对)有什么区别self.quips
。后者是我一直看到的方式,但是在这里使用的方式有所不同。我的第一个想法是也许它绕过了先创建对象的需要,但是在本示例中self.quips
,无论如何还是需要对象。
本质上,他们在方案中完成了同样的事情。Death.quips
正在调用该类的quips属性。使用self.quips是指该类的特定对象。您也可以更改对象的属性。
例如,如果更改Death.quips
为,则self.quips
可以执行以下操作:
>>> a = Death()
>>> a.enter()
Such a luser.
>>> a.quips = [
"a",
"b",
"c",
"d",
"e"
]
>>> a.enter()
c
>>>
但是,如果将其保留为Death.quips,则结果如下:
>>> a = Death()
>>> a.enter()
You died. You kinda suck at this.
>>> a.quips = [
"a",
"b",
"c",
"d",
"e"
]
>>> a.enter()
Such a luser.
>>>
Self
引用实例化对象的属性,而Death
引用整个类的不变属性。
我希望这会有所帮助并且有意义
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句