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

问题描述 投票:1回答:1

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

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代替花的名称如何跳过我不想进入类的构造函数的值

python python-3.x constructor
1个回答
2
投票

你有3个可选参数。如果你传递它们而不告诉你使用哪一个(就像你做的那样),则假设它是从左到右。这意味着

F2=Flower(9,78.9)

被解释为

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

price获取默认值。要明确地解决这个问题,请写出你的意思。在您的情况下,它应该是以下内容:

F2=Flower(noPedals=9, price=78.9)
© www.soinside.com 2019 - 2024. All rights reserved.