Skip to main content
 首页 » 编程设计

python之使用类方法实现替代构造函数,如何向这些替代构造函数添加函数

2025年05月04日15freeliver54

我有一个可以使用类方法通过替代构造函数构造的类。

class A: 
 
    def __init__(self, a, b): 
            self.a = a 
            self.b = b 
 
    @classmethod 
    def empty(cls, b): 
        return cls( 0 , b) 

所以让我们说,不用像 A() 那样构造 A,我现在也可以做 A.empty()。

为了方便用户,我想进一步扩展这个empty方法,这样我就可以通过A.empty()初始化A > 以及更专业但密切相关的 A.empty.typeI() 和 A.empty.typeII()。

我天真的方法并没有完全达到我的要求:

class A: 
 
    def __init__(self, a, b): 
            self.a = a 
            self.b = b 
 
    @classmethod 
    def empty(cls, b): 
 
        def TypeI(b): 
            return cls( 0 , b-1) 
 
        def TypeII(b): 
            return cls( 0 , b-2) 
 
        return cls( 0 , b) 

谁能告诉我如何做到这一点(或者至少说服我为什么那会是个糟糕的主意)。我想强调的是,对于使用,我认为这种方法对于用户来说非常方便和清晰,因为功能被直观地分组。

请您参考如下方法:

您可以通过使 Empty 成为 A 的嵌套类而不是类方法来实现您想要的。最重要的是,这提供了一个方便的命名空间——永远不会创建它的实例——在其中放置各种替代构造函数并且可以轻松扩展。

class A(object): 
    def __init__(self, a, b): 
        self.a = a 
        self.b = b 
 
    def __repr__(self): 
        return 'A({}, {})'.format(self.a, self.b) 
 
    class Empty(object):  # nested class 
        def __new__(cls, b): 
            return A(0, b)  # ignore cls & return instance of enclosing class 
 
        @staticmethod 
        def TypeI(b): 
            return A(0, b-1) 
 
        @staticmethod 
        def TypeII(b): 
            return A(0, b-2) 
 
a = A(1, 1) 
print('a: {}'.format(a))      # --> a: A(1, 1) 
b = A.Empty(2) 
print('b: {}'.format(b))      # --> b: A(0, 2) 
bi = A.Empty.TypeI(4) 
print('bi: {}'.format(bi))    # --> bi: A(0, 3) 
bii = A.Empty.TypeII(6) 
print('bii: {}'.format(bii))  # --> bii: A(0, 4)