Is there any way to create an empty constructor in python. I have a class:

class Point:def __init__(self, x, y, z):self.x = xself.y = yself.z = z

now I initialize it like this:

p = Point(0, 5, 10)

How can I create an empty constructor and initialize it like this:

p = Point()
4

Best Answer


class Point:def __init__(self):pass

As @jonrsharpe said in comments, you can use the default arguments.

class Point:def __init__(self, x=0, y=0, z=0):self.x = xself.y = yself.z = z

Now you can call Point()

You can achieve your desired results by constructing the class in a slightly different manner.

class Point:def __init__(self):passdef setvalues(self, x, y, z):self.x = xself.y = yself.z = z

You should define the __init__() method of your Point class with optional parameters.

In your case, this should work:

class Point:def __init__(self, x=0, y=0, z=0):self.x = xself.y = yself.z = zpointA = Point(0, 5, 10)print("pointA: x={}, y={}, z={}".format(pointA.x, pointA.y, pointA.z))# print "pointA: x=0, y=5, z=10"pointB = Point()print("pointB: x={}, y={}, z={}".format(pointB.x, pointB.y, pointB.z))# print "pointB: x=0, y=0, z=0"