-1

I wrote a Python program to calculate the cost of a land. Why can't I just write "Land.cost() instead of "Land(0,0,0).cost()" inside print function?

class Land:
    def __init__(self, length, width, unitcost):
        self.length = input ('length :')
        self.breadth = input('width :')
        self.unitcost = input('unitcost :')

    def cost(self):
        return int(self.length) * int(self.breadth) * int(self.unitcost)

print ( 'Cost of Land is: $' + str(  Land(0,0,0).cost()  ) )
Ronald
  • 21
  • 6
  • Your question is unclear. Is it about having default values, about calling a method on a class... ? What would you like to write if the arguments were `1, 1, 1` ? Please clarify! – Thierry Lathuille May 17 '20 at 12:10

3 Answers3

1

land is an object that you need to create before using, and to create it you use the constructor defined by init. as you can see your constructor has 3 parameters other than self that you need to specify when creating the object

class Land:
    def __init__(self, length, width, unitcost):
        self.length = input ('length :')
        self.breadth = input('width :')
        self.unitcost = input('unitcost :')

    def cost(self):
        return int(self.length) * int(self.breadth) * int(self.unitcost)

land = new Land(0,0,0)
print ( 'Cost of Land is: $' + str(  land.cost()  ) )
SalahM
  • 74
  • 2
1

With Land(0,0,0) you are calling the constructor for the Land class and returning an object of Land . Which will have the method cost. So you would have to create an object and then call the cost function.

Generally you would have to create an object of a class before you can call its member functions.

object = Land(0,0,0)
print ( 'Cost of Land is: $' + str(  object.cost()  ) )

The above code creates an object of type land which will call the function cost.

0

The short answer is: because that's not conventionally how expressions in Python are written. The syntax of programming languages is often reminiscent of the syntax of written mathematics in specific ways, but it is its own thing and you can't necessarily expect to be able to get away with what are, formally speaking abuses of notation.

Now Python is a flexible language and I'm pretty certain that you could create an object Land which would behave like what you're asking for. But you would be better off getting used to the differences between writing program code and writing mathematics for a human.

Hammerite
  • 21,755
  • 6
  • 70
  • 91
  • Can you change the above code from mathematics to program code?? – Ronald May 17 '20 at 12:28
  • Like I said, yes technically you can do that. I believe you would need to create a class that defines __call__() to return a new instance of the class, and then define Land to be an instance of that class initialised as classname(0, 0, 0). But I recommend you get used to how Python wants you to write things instead. – Hammerite May 17 '20 at 12:36