【问题标题】:Python - inherit default class value if the variable has a specific valuePython - 如果变量具有特定值,则继承默认类值
【发布时间】:2023-02-07 02:21:50
【问题描述】:

一个非常简单的问题,但我需要一些帮助。我创建了一个具有一些默认值的类。之后,实例根据输入获取值。如果其中一个属性为“null”,我该如何为其分配默认值?

class Dragon:
    dragons=[]

    def __init__(self,dragon_type,name,health=2000,attack=450,fly_speed=120):
        self.dragon_type=dragon_type
        self.name=name
        self.health=health
        self.attack=attack
        self.fly_speed=fly_speed

        Dragon.dragons.append(self)

num=int(input())

for n in range(num):
    entry=input().split() #fire Azzaaxx null 480 null
    dragon_type,name,health,attack,fly_speed=entry[0],entry[1],entry[2],entry[3],entry[4]
    if health=="null":
        health=... #2000
    else:
        health=int(health)
    if attack=="null":
        attack=... #450
    else:
        attack=int(attack)
    if fly_speed=="null":
        fly_speed=... #120
    else:
        fly_speed=int(fly_speed)
    obj=Dragon(dragon_type,name,health,attack,fly_speed)

这种方法是可以接受的还是应该有不同的定义? 先感谢您!

【问题讨论】:

    标签: python class oop inheritance default-value


    【解决方案1】:

    更改类定义,以便将 None 值转换为默认值。

    class Dragon:
        dragons=[]
    
        def __init__(self,dragon_type,name,health=None,attack=None,fly_speed=None):
            self.dragon_type=dragon_type
            self.name=name
            self.health=health if health is not None else 2000
            self.attack=attack if attack is not None else 450
            self.fly_speed=fly_speed if fly_speed is not None else 120
    
            Dragon.dragons.append(self)
    

    然后,如果用户输入null,您可以将调用程序中的变量设置为None__init__()方法将做正确的事情,因此您不必重复默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2016-09-10
      • 2012-03-06
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多