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

标签 python python-3.x constructor

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

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/

相关文章:

python - functools.partial 作为 IronPython 事件处理程序

python - ASP.net MVC : How to access project from mobile via Local Server

python - 如何在cython中编译pyqt5和python代码

python - pandas 在尝试获取 timedelta 对象天数时将 NaT 替换为列中的字符串

python - 晨星数据导入不会给出所要求的所有日期价格

python - PyCharm 自动打开

python - 如何为 python 3.0 的仅关键字参数导入 __future__?

c++ - 一个最令人头疼的解析错误 : constructor with no arguments

java - 不允许在调用 super 构造函数时使用实例变量和方法

c++ - 不止一个构造匹配参数列表