【问题标题】:How to get 3 inputs in one variables using class method如何使用类方法在一个变量中获取 3 个输入
【发布时间】:2021-04-23 14:11:29
【问题描述】:
class Student:
    def __init__(self, chemistry, english, math):
        self.chemistry = chemistry
        self.english = english
        self.math = math

    def chemistry(self):
        return self.chemistry

    def english(self):
        return self.english

    def math(self):
        return self.math

    def tot(self):
        return self.chemistry + self.english + self.math

answer = Student(100,20,30)
answer.tot()
print(answer.tot())

我想知道如何在一个变量中获得 3 个输入。我尝试过使用“列表”,但没有成功。

【问题讨论】:

标签: python class variables input


【解决方案1】:

说明

您可以使用listtuple 作为一个变量,例如使用名为add 的函数(添加两个数字):

def add(a, b):
    return a + b

print(add(3, 8))


def add(nums):
    return nums[0] + nums[1]

print(add([3,8])) # List
print(add((3,8))) # Tuple

代码:

类:

class Student:
    def __init__(self, subjects):
        self.chemistry = subjects[0]
        self.english = subjects[1]
        self.math = subjects[2]

    # Your Methods, consider renaming them

初始化类:

answer = Student([100,20,30]) # Using a List
answer = Student((100,20,30)) # Using a Tuple

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多