1

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.

3
  • Is there any other way I have achieve this method Commented Jan 31, 2020 at 7:15
  • In Python you are using dynamic function arguments with defaults like def __init__(para1=None, para2=None, para3=None) where None can be any default value. See docs.python.org/3/reference/… for details! Commented Jan 31, 2020 at 7:15
  • Python does not supports method overloading like C++ Commented Jan 31, 2020 at 7:28

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.