Gaurav Dubey
Gaurav Dubey

Reputation: 305

Python Object initialization,_init_ method

How Can I create class if i have to create object for my class like below.

Obj1 = Class()
Obj2 = Class(para1,para2,para3)

This is related to a task that i need to complete just started learning Python.

I tried construction overloading but it seems to not work in Python .Can anyone tell me how can i achieve this or it is technically wrong to have both line in one code.

Upvotes: 1

Views: 62

Answers (2)

Alper
Alper

Reputation: 495

If you set default values like length = 80, you don't have to set them. But if you set the values, it ll be set as you wish. The following code demonstrates almost what you want.

class Rectangle:
   def __init__(self, length = 80, breadth = 60, unit_cost=100):
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost

   def get_perimeter(self):
       return 2 * (self.length + self.breadth)

   def get_area(self):
       return self.length * self.breadth

   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# r = Rectangle() <- this returns with default values
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))

Upvotes: 1

Sociopath
Sociopath

Reputation: 13426

You can use *args or **kwargs

class Class1:
    def __init__(self, *args):
        pass


obj1 = Class1()
obj2 = Class1(para1,para2,para3)

or

class Class1:
    def __init__(self, **kwargs):
        pass


obj1 = Class1()
obj2 = Class1(para1=para1,para2=para2,para3=para3)

Refer this to learn more about *args and **kwargs

Upvotes: 2

Related Questions