python将参数从\uuuu new\uuuuu传输到\uuuu init__

2024-06-28 11:01:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在运行init之前,我尝试更改参数,但它没有更改,并且保持为主中给出的第一个参数,如何更改新的中的参数?你知道吗

class A(object):
            def __init__(self,ip,st):
                    print 'A arrived to init '+st
                    self.ip=ip

        def __new__(cls,ip,st):
                print "A arrived to new"
                if ip>10:
                        return object.__new__(cls,ip,"A")
while True:                
        s=input("input?")
        a=A(s,"a")
        print type(a)

输出:

input?88
A arrived to new
A arrived to init a
<class '__main__.A'>
input?44
A arrived to new
A arrived to init a
<class '__main__.A'>
input?22
A arrived to new
A arrived to init a
<class '__main__.A'>
input?12
A arrived to new
A arrived to init a
<class '__main__.A'>

Tags: toselfipnewinput参数objectinit
1条回答
网友
1楼 · 发布于 2024-06-28 11:01:17

它是元类的__call__()方法,每次传递它接收到的参数时都调用YourClass.__new__()YourClass.__init__()。因此,如果要在参数到达YourClass.__init__()之前更改参数,有两种解决方案:修饰__init__()或使用自定义元类重写type.__call__()。你知道吗

(Q&D)装饰器版本:

def changeargs(func):
    # fixme : make this a well-behaved decorator
    def wrapper(self, *args, **kw):
        print("changearg.wrapper(%s, %s)" % (args, kw))
        args = (1, 2)
        kw = {"hacked": True}
        return func(self, *args, **kw)
    return wrapper

class Bar(object):
    @changeargs
    def __init__(self, *args, **kw):
        self.args = args
        self.kw = kw

    def __repr__(self):
        return "<Bar(%s, %s)>" % (self.args, self.kw)

(Q&D)元类版本(py 2.7.x):

class FooType(type):
    def __call__(self, *args, **kw):
        print("FooType.__call__(%s, %s)" % (args, kw))
        args = (1, 2)
        kw = {"hacked": True}
        # fixme : make this collaborative super() call
        return type.__call__(self, *args, **kw)

class Foo(object):
    __metaclass__ = FooType

    def __init__(self, *args, **kw):
        self.args = args
        self.kw = kw

    def __repr__(self):
        return "<Foo(%s, %s)>" % (self.args, self.kw)

但正如Rawing在评论中正确地提到的那样,您可以直接在类__init__方法中执行此操作。你知道吗

相关问题 更多 >