我知道创建一个自定义__repr__
或__add__
方法(以此类推),以修改操作符和函数的行为。 len
有没有方法覆盖?是否可以修改len()的行为?
例如:
class Foo:
def __repr__(self):
return "A wild Foo Class in its natural habitat."
foo = Foo()
print(foo) # A wild Foo Class in its natural habitat.
print(repr(foo)) # A wild Foo Class in its natural habitat.
会这样做了len
,与列表?通常情况下,它应该是这样的:
foo = []
print(len(foo)) # 0
foo = [1, 2, 3]
print(len(foo)) # 3
如果我要离开搜索类型出计的?就像这样:
class Bar(list):
pass
foo = [Bar(), 1, '']
print(len(foo)) # 3
count = 0
for item in foo:
if not isinstance(item, Bar):
count += 1
print(count) # 2
有没有办法从list
子内做到这一点?
你已经有很好的答案,但如果你想了解更多关于魔术方法我可以建议[A指南Python的魔术方法(HTTP:// WWW。 rafekettler.com/magicmethods.html);) – swenzel
这会派上用场!感谢分享。 @swenzel –
你有一个列表子类,而不是一个列表超类。 – wim