简体   繁体   中英

Constructing a class in python without directly calling the constructor

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?

With a static method:

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

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

s = Start.make()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM