Modifying class variable before __new__

问题描述 投票:0回答:1
我想修改类的类变量

bar

,以便将A对象的创建用
bar2
而不是
bar1
执行

class A(object): def __new__(cls, foo): obj = super(A, cls).__new__(cls) return obj class B(A): bar = "bar1" def __new__(cls, foo=bar): print("actual",foo) rm = super().__new__(cls,foo=foo) return rm if __name__ == '__main__': B.bar = 'bar2' b = B() print(b.bar)
when I run the code I get:

actual bar1 bar2
whereas I'm expecting:

actual bar2 bar2
    
python class variables metaclass
1个回答
0
投票
Just use the normal

__init__

 approach instead.您可以转发您需要的任何默认论点:

class A: def __init__(self, *args, **kwargs): print(f"A.__init__ got bar={kwargs.get('bar')}") class B(A): bar = "bar1" def __init__(self, *args, **kwargs): if 'bar' not in kwargs: kwargs['bar'] = B.bar super().__init__(self, *args, **kwargs) print(B().bar, B(bar="lol").bar)
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.