【问题标题】:How to call only the second value of a class in python, while keeping the first value as default?如何在python中只调用类的第二个值,同时保持第一个值为默认值?
【发布时间】:2021-01-31 19:35:53
【问题描述】:

在变量y 中,我只想调用第二个值,即age,同时将第一个值(height)保持为默认值。我该怎么做?

class person():
    def __init__(self, height=130, age=20):
        self.height = height
        self.age = age

    def convert_height(self):
        return self.height / 10

    def find_birth_year(self, p_year):
        return p_year - self.age


x = person(170)
y = person(, 32) # How to have default value for height here?

print(x.height, x.age)
print(y.height, y.age)
print(x.convert_height(), x.find_birth_year(2020))
print(y.convert_height(), y.find_birth_year(2020))

【问题讨论】:

  • 请考虑接受最有帮助和最完整的答案 ;) 为下一个将来到这里

标签: python class arguments


【解决方案1】:

您可以使用keyword 参数:使用它的名称和它在方法中的位置

class person():
    def __init__(self, height=130, age=20):
        self.height = height
        self.age = age
    
if __name__ == '__main__':
    x = person(170)
    y = person(age=32)

这里是some more

【讨论】:

    【解决方案2】:

    使用关键字参数:

    y = person(age=32)

    【讨论】:

    • 没问题,如果有帮助,请考虑使用左侧的勾号将其标记为“正确答案”。
    猜你喜欢
    • 2016-04-24
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2013-05-05
    • 2021-04-28
    相关资源
    最近更新 更多