gpt4 book ai didi

python - 在 python 中初始化变量,一些变量来自构造函数,一些变量来自用户

转载 作者:行者123 更新时间:2023-12-01 02:05:49 25 4
gpt4 key购买 nike

我正在编写一个程序,我想从构造函数中初始化一些变量,并从用户的输入中初始化其他变量

class Flower():
def __init__(self, ftype="rose",noPedals=6,price=12.23):
self._ftype=ftype
self._noPedals=noPedals
self._price=price
def setFtype(self, ftype):
self._ftype=ftype
def setNoPedal(self, noPedals):
self._noPedals=noPedals

def setPrice(self, price):
self._price=price

def getFtype(self):
return self._ftype
def getNoPedal(self):
return self._noPedals
def getPrice(self):
return self._price

if __name__=="__main__":
F1=Flower()
print("The first flower is ",F1.getFtype()," its has ",F1.getNoPedal()," pedals and its price is ",F1.getPrice())
F1.setFtype("Lily")
F1.setNoPedal(4)
F1.setPrice(20)
print("Now the first flower is ",F1.getFtype()," its has ",F1.getNoPedal()," pedals and its price is ",F1.getPrice())
F2=Flower(9,78.9)
print("The second flower is ",F2.getFtype()," its has ",F2.getNoPedal()," pedals and its price is ",F2.getPrice())

我得到输出, 第一朵花是玫瑰,有6瓣,价格是12.23 现在第一朵花是百合,有4个踏板,价格是20 第二朵花是 9,踏板数为 78.9,价格为 12.23

我用 9 代替花名,如何跳过我不想输入到类构造函数中的值

最佳答案

您有 3 个可选参数。如果您通过它们而不告诉您使用哪些(就像您所做的那样),则假定是从左到右。这意味着

F2=Flower(9,78.9)

被解释为

F2=Flower(ftype=9,noPedals=78.9)

price 获取默认值。要解决这个问题,请明确写出您想要的参数。在您的情况下,它应该如下:

F2=Flower(noPedals=9, price=78.9)

关于python - 在 python 中初始化变量,一些变量来自构造函数,一些变量来自用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49085416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com