Python 如何在创建过程中将属性分配给实例?
我仍在学习Python,对创建新实例有点困惑。在本例的底部,我创建了一个BgImages实例。我想给它分配一个字符串,所以我添加了collidetext=这是一个测试,然后我进入BgImages构造函数,简单地将self.collidetext=随机字符串。问题是当我打印slum.collisiontext时,它仍然打印随机字符串,而不是测试 我已经向其他人寻求帮助,现在我明白这与**kwargs不允许我尝试做的事情有关。我希望有人能告诉我,我如何才能实现我正在努力实现的目标,以及为什么我所做的不符合外行的标准Python 如何在创建过程中将属性分配给实例?,python,Python,我仍在学习Python,对创建新实例有点困惑。在本例的底部,我创建了一个BgImages实例。我想给它分配一个字符串,所以我添加了collidetext=这是一个测试,然后我进入BgImages构造函数,简单地将self.collidetext=随机字符串。问题是当我打印slum.collisiontext时,它仍然打印随机字符串,而不是测试 我已经向其他人寻求帮助,现在我明白这与**kwargs不允许我尝试做的事情有关。我希望有人能告诉我,我如何才能实现我正在努力实现的目标,以及为什么我所做的
class BgImages(ButtonBehavior, Image):
def __init__(self, **kwargs):
super(Npcs, self).__init__(**kwargs)
self.collidetext="random string"
def collisiontext(self,**kwargs):
return self.collidetext()
class MainCharacter(Image):
def __init__(self, **kwargs):
super(MainCharacter, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(None, self)
if not self._keyboard:
return
self._keyboard.bind(on_key_down=self.on_keyboard_down)
self._keyboard.bind(on_key_up=self.on_keyboard_up)
class gameApp(App):
def build(self):
slum=BgImages(source='slum.png', collidetext="this is a test1")
police=BgImages(source='police.png', collidetext="this is a test2")
listofwidgets=[]
listofwidgets.append(slum)
listofwidgets.append(police)
我想你可能会把这个问题和你使用的kwargs混淆了。但无论如何,要在当前代码中实现您想要的功能,您可以执行以下操作:
def __init__(self, **kwargs):
super(Npcs, self).__init__(**kwargs)
self.collidetext=kwargs["collidetext"]
def __init__(self, source=None, collidetext=None):
super(Npcs, self).__init__(source=source)
self.collidetext=collidetext
但是,通常您会使用实际的命名参数,可能如下所示:
def __init__(self, **kwargs):
super(Npcs, self).__init__(**kwargs)
self.collidetext=kwargs["collidetext"]
def __init__(self, source=None, collidetext=None):
super(Npcs, self).__init__(source=source)
self.collidetext=collidetext
另外,您使用def collisiontextself,**kwargs:表示您不确定kwargs的用途,您只是在重复该模式。我建议在进一步学习之前花些时间学习一本好的Python教程。您正确地传递了所需的关键字参数,但没有在目标类中使用它们
class BgImages(ButtonBehavior, Image):
def __init__(self, **kwargs):
super(Npcs, self).__init__(**kwargs)
# do a dictionary lookup to get a random string if the argument is not passed
self.collidetext= kwargs.get("collidetext","random string")
我使用了你的最下面的示例,虽然source=None使我所有的图像都消失了,所以我删除了该部分。谢谢你的帮助,但我不明白为什么没有source=None它就不能工作。是的,这就是为什么我建议花些时间学习Python教程的原因。例如,请深入解释函数参数。它们使用的语言过于密集,我以前已经阅读过本教程。信不信由你,这是我尝试学习Python的第二年,我的水平仍然很低。您是否可以推荐其他教程或文档,以便我理解函数参数?其他流行的Python教程包括和。