Using a class' __new__ method as a Factory: __init__ gets called twice

前端 未结 3 1719
南旧
南旧 2020-12-04 19:15

I encountered a strange bug in python where using the __new__ method of a class as a factory would lead to the __init__ method of the instantiated

3条回答
  •  没有蜡笔的小新
    2020-12-04 20:13

    After posting my question, I continued searching for a solution an found a way to solve the problem that looks like a bit of a hack. It is inferior to Duncan's solution, but I thought it could be interesting to mention none the less. The Shapeclass becomes:

    class ShapeFactory(type):
        def __call__(cls, desc):
            if cls is Shape:
                if desc == 'big':   return Rectangle(desc)
                if desc == 'small': return Triangle(desc)
            return type.__call__(cls, desc)
    
    class Shape(object):
        __metaclass__ = ShapeFactory 
        def __init__(self, desc):
            print "init called"
            self.desc = desc
    

提交回复
热议问题