37

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 = x
        self.y = y
        self.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()
1
  • 3
    And what should the x, y and z of the second version be? Don't you just want default arguments? Have you tried reading a tutorial or doing some research? Commented Mar 19, 2017 at 9:10

4 Answers 4

56
class Point:
    def __init__(self):
        pass
Sign up to request clarification or add additional context in comments.

3 Comments

But this cannot coexist with the current implementation. Only one method with that name will be retained.
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
In place of "pass", "1" also would have worked, or any null operation. See more: docs.python.org/2.0/ref/pass.html
26

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

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

Now you can call Point()

1 Comment

This works, but be careful. Passing over any mutable types (objects, arrays...) will make it shared between all instances.
15

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

class Point:
    def __init__(self):
        pass

    def setvalues(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    

2 Comments

Shouldn't setvalues take 'self' as the first argument? Also, shouldn't all those instance variables be defined in __init__?
@RCross yeah it should have self as the first arg, edited to reflect. The constructor wouldn't be empty if we had instance variable declarations in it however. I agree that it isn't pythonic however.
13

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 = x
        self.y = y
        self.z = z

pointA = 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"

1 Comment

This is the best answer. It covers all of the ground that the original question asks about.

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.