gpt4 book ai didi

python - 你如何躲避 hasattr?

转载 作者:太空宇宙 更新时间:2023-11-04 10:19:15 25 4
gpt4 key购买 nike

假设一个函数查看一个对象并检查它是否具有函数 a_method:

def func(obj):
if hasattr(obj, 'a_method'):
...
else:
...

我有一个对象,其类定义了 a_method,但我想隐藏 hasattr。我不想更改 func 的实现来实现这种隐藏,那么我可以做些什么来解决这个问题?

最佳答案

如果该方法是在类上定义的,您似乎可以将其从类的 __dict__ 中删除。这会阻止查找(hasattr 将返回 false)。如果您在删除它时保留对它的引用(如示例),您仍然可以使用该函数 - 请记住,您必须为自己传递一个类的实例,它不是用隐含的 self 调用的.

>>> class A:
... def meth(self):
... print "In method."
...
>>>
>>> a = A()
>>> a.meth
<bound method A.meth of <__main__.A instance at 0x0218AB48>>
>>> fn = A.__dict__.pop('meth')
>>> hasattr(a, 'meth')
False
>>> a.meth
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'meth'
>>> fn()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: meth() takes exactly 1 argument (0 given)
>>> fn(a)
In method.

关于python - 你如何躲避 hasattr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com