【发布时间】: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