【问题标题】:Send input from function to class将输入从函数发送到类
【发布时间】:2021-06-21 04:55:15
【问题描述】:

这里是 Python 初学者。
我很难理解如何从函数中获取用户输入以在我的类方法之一中使用它

class...
    def setFirstStageSpeed(self, s):
        s = # FIRST_STAGE_SPEED from main()
        self.Speed = s

...

def main():
    FIRST_STAGE_SPEED = 0
    while True:
        try:
            FIRST_STAGE_SPEED = int(input("Please set first stage speed"
                                           "for the spacecraft: "))
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue
        if FIRST_STAGE_SPEED < 0:
            print("Sorry, your response must not be negative.")
            continue
        else:
            break
...

如上所示,我试图将 FIRST_STAGE_SPEED 上的输入值传递给 setFirstStageSpeed() 方法。

【问题讨论】:

  • 您可以致电 yourInstanceOfClass.setFirstStageSpeed(FIRST_STAGE_SPEED),这样。您需要先创建该类的一个实例,尽管您实际上并没有告诉我们该类的名称是什么。

标签: python-3.x class object input


【解决方案1】:

这是一个解决方案。你应该创建一个 SpaceCraft 实例。这是 OOP 样式。

class SpaceCraft:
    def setFirstStageSpeed(self, s):
        self.Speed = s


def main():
    FIRST_STAGE_SPEED = 0
    while True:
        try:
            FIRST_STAGE_SPEED = int(input("Please set first stage speed"
                                           "for the spacecraft: "))
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue
        if FIRST_STAGE_SPEED < 0:
            print("Sorry, your response must not be negative.")
            continue
        else:
            break

    # make a instance of SpaceCraft.if you not familiar with OOP(Object-oriented programing).you should study about it
    spaceCraft = SpaceCraft()
    # then call the instance method.set the first stage speed
    spaceCraft.setFirstStageSpeed(FIRST_STAGE_SPEED)

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    相关资源
    最近更新 更多