简体   繁体   English

在python中构造一个class而不直接调用构造函数

[英]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...在 python 中,如果我们定义一个名为 Start 的 class 并使用如下所示的参数对其进行初始化...

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? 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.我要做的是让 Start.make 完成与Start(1)相同的目标,因此我可以潜在地创建其他构造常用值的方法,而无需手动将 arguments 放入Start()构造函数中。 Is this in anyway possible in Python?这在 Python 中是否可能? If not, are there any alternatives solutions I can follow to achieve a similar result?如果没有,我可以遵循任何替代解决方案来达到类似的结果吗?

With a static method:使用 static 方法:

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:您可以使用 static 方法,也可以使用 class 方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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