除了has调用的类之外,还有其他类型吗

2024-04-23 18:07:17 发布

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

对于代码:

class a(object):
    a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')

谁能被hasattr称为除了'班某人'?你知道吗

谢谢!你知道吗


Tags: 代码objectclasshasattrprintaaa
2条回答

您可以使用任何对象作为第一个参数(任何字符串作为第二个参数)调用hasattr:如果该对象没有该名称的属性,它只返回False(“having”属性当然可能包括继承或合成它;^当且仅当访问x.y不会引发异常时,{}才是真的,这就是它内部的工作方式:它尝试getattr并捕获异常(如果有)。你知道吗

根据Python文档,必须传递一个对象作为hasttr()函数的参数。你知道吗

hasattr(object, name): The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)

相关问题 更多 >