忽略函数 f() 的可选返回值的首选方法是什么?
A)
foo, _ = f()
Run Code Online (Sandbox Code Playgroud)
b)
foo = f()[0]
Run Code Online (Sandbox Code Playgroud)
C)
def f(return_bar=True):
if return_bar:
return foo, bar
else:
return foo
foo = f(return_bar=False)
Run Code Online (Sandbox Code Playgroud) 我有一个自定义类实现 __add__ 和 __radd__ 作为
import numpy
class Foo(object):
def __init__(self, val):
self.val = val
def __add__(self, other):
print('__add__')
print('type self = %s' % type(self))
print('type other = %s' % type(other))
return self.val + other
def __radd__(self, other):
print('__radd__')
print('type self = %s' % type(self))
print('type other = %s' % type(other))
return other + self.val
Run Code Online (Sandbox Code Playgroud)
我首先测试 __add__
r1 = Foo(numpy.arange(3)) + numpy.arange(3,6)
print('type results = %s' % type(r1))
print('result = {}'.format(r1))
Run Code Online (Sandbox Code Playgroud)
它导致了预期的结果
>>> __add__
>>> type self = <class '__main__.Foo'> …
Run Code Online (Sandbox Code Playgroud)