1

In python if we define a class called Start and initialize it with an argument as seen below...

class Start:
   def __init__(self, a):
      self.a = a

Once defined, and after importing Start into another python file is there any way to make a function or attribute inside the class so I can construct the class directly like this?

# Start.make or Start.make()
# Sample usage below
s = Start.make #initializes Start with the argument of 1

What I'm trying to do is to have Start.make accomplish the same objective as Start(1) so I can potentially create other method of constructing commonly used values without having to manually place the arguments inside the Start() constructor. Is this in anyway possible in Python? If not, are there any alternatives solutions I can follow to achieve a similar result?

2 Answers 2

1

You can use a static method, or you can also use a class method:

class Start:
    def __init__(self, a):
        self.a = a

    @classmethod
    def make(cls):
        return cls(1)

To create an instance use the following:

>>> s = Start.make()
>>> s.a
1
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what class methods are intended for: defining alternate constructors for a class.
1

With a static method:

class Start:
    def __init__(self, a):
        self.a = a

    @staticmethod
    def make():
        return Start(1)

s = Start.make()

2 Comments

Are there any caveats to using a static method in python?
@PensivePastuer make will always return an instance of Start, even if you subclass Start. A class method is more flexible; static methods aren't commonly used in Python, as they essentially just wrap a regular function in the namespace of a class.

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.