如何有效地调用多个变量的方法



这是我的程序中的一行代码:

self.startcash, self.price, self.highroll, self.lowroll = self.prompt_user()

您在这里看到的是我试图从一个方法调用中获取多个变量。根据我对政治公众人物的理解,把这么多变量放在一行是不明智的。有没有什么方法可以缩短这些自调用/将其分解为多行,而不需要多次调用prompt_user方法?

注意:Prompt_user所做的是从用户那里获得变量的输入。

如果您真的想让它更简短、更可读,那么您可以只使用元组索引,但这可能是一个可读性较差的选项。就我个人而言,我不认为你现在拥有它有什么错,只要你不在任何地方都拥有它。但无论如何,你可以转换你的线路:

self.startcash, self.price, self.highroll, self.lowroll = self.prompt_user()

到此:

output = self.prompt_user()
self.startcash = output[0]
self.price = output[1]
self.highroll = output[2]
self.lowroll = output[3]

我知道的最好方法是在__init__中将它们全部设置为None(或某些默认值(

self.startcash = self.price = self.highroll = self.lowroll = None  # can make multiple lines

然后在prompt_user函数中,您可以使用self设置变量,因为您使用的是OOP

def prompt_user(self):
self.startcast = input('startcash: ')
self.price = input('price: ')
self.highroll = input('highroll: ')
self.lowroll = input('lowroll: ')

最新更新