Waqas Khan
Waqas Khan

Reputation: 79

Initialing variables some variables from constructor and some from user in python

I am writing a program and I want to initialize some variables from the constructor and others from the input of user for example

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())

I am getting the output, The first flower is rose its has 6 pedals and its price is 12.23 Now the first flower is Lily its has 4 pedals and its price is 20 The second flower is 9 its has 78.9 pedals and its price is 12.23

I am getting 9 inplace of the name of the flower how do I skip the values I do not want to enter into the constructor of the class

Upvotes: 1

Views: 61

Answers (1)

ViG
ViG

Reputation: 1868

You have 3 optional arguments. If you pass them without telling which ones you use (like you did) it is assumed to be from left to right. This means that

F2=Flower(9,78.9)

is interpreted as

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

and price gets the default value. To solve this explicitly write which argument you mean. In your case it should be the following:

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

Upvotes: 2

Related Questions