简体   繁体   English

传递函数中的对象作为参数的魔术方法?

[英]magic method for passing object in function as argument?

Is there any magic method that will invoke when I pass object as argument of function? 当我将对象作为函数的参数传递时,是否有任何魔术方法可以调用?

class Test:
    def __init__(self, a, b):
         self.a = a
         self.b = b
    def __???__(self):
         return (self.a, self.b)

test = Test(0, 1)

some_function(test) # I'd like to pass parameters (0, 1) here

No, arguments to functions are not treated special in any way. 不,函数的参数不会以任何方式被特殊对待。 It's just another assignment (to the parameter names of the function). 这只是另一个分配(分配给函数的参数名称)。

If you need to treat a and b as separate arguments, make Test a sequence , then pass it in with the *sequence call syntax to expand the sequence to separate arguments. 如果需要将ab视为单独的参数,请使Test一个序列 ,然后将其传递给*sequence调用语法以将序列扩展为单独的参数。 You can make it a sequence by making it an iterator type : 您可以通过将其设为迭代器类型来使其成为序列:

class Test:
    def __init__(self, a, b):
         self.a = a
         self.b = b
    def __iter__(self):
         return iter((self.a, self.b))

test = Test(0, 1)
some_function(*test)

Demo: 演示:

>>> def some_function(a, b):
...     print(f'a = {a!r}\nb = {b!r}')
...
>>> test = Test(0, 1)
>>> some_function(*test)
a = 0
b = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM