[如何在仍然使用`class`关键字的同时覆盖构造函数? [重复]

问题描述 投票:-2回答:1

此问题已经在这里有了答案:

创建类的两种著名方法如下:

class Klass:
    pass

Klass = type("Klass", tuple(), dict())

我想重写构造函数(__call__),同时仍使用class关键字而不是做其他事情,例如直接调用type。我确实想覆盖(__call__),而不是__init__

我的失败尝试如下所示:

尝试1

class Foo:
    @classmethod
    def __call__(*args):
        print("arr har")
        return super(type(args[0]), args[0]).__call__(*args)

instance = Foo()
# did not print "arr har"

尝试2

class BarMeta(type):
    def __call__(*args):
        print("hello world")
        return super(type(args[0]), args[0]).__call__(*args[1:])
  • 尝试2A

    class Bar:
        __metaclass__ = BarMeta
    
    instance = Bar()
    # did not print "hello world" 
    
  • 尝试2B

    Baz = BarMeta("Baz", tuple(), dict())
    instance = Baz()
    # Did print "hello world," but we weren't able to use the `class` keyword to create `Baz`
    
python python-3.x metaprogramming metaclass constructor-overloading
1个回答
0
投票

[所有功劳归Aran-Fey,他将答案发布为评论,而不是答案:

class BarMeta(type):
    def __call__(*args):
        print("hello world")
        return super(type(args[0]), args[0]).__call__(*args[1:])    

class Bar(metaclass=BarMeta):
    pass

instance = Bar()
© www.soinside.com 2019 - 2024. All rights reserved.