有没有办法在Python中确定对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
Run Code Online (Sandbox Code Playgroud)
在使用之前如何判断是否a具有该属性property?
我可以用吗:
if A:
Run Code Online (Sandbox Code Playgroud)
代替
if A is not None:
Run Code Online (Sandbox Code Playgroud)
后者似乎很冗长.有区别吗?
哪种方法可以检查属性是否存在?
Jarret Hardie提供了这个答案:
if hasattr(a, 'property'):
a.property
Run Code Online (Sandbox Code Playgroud)
我看到它也可以这样做:
if 'property' in a.__dict__:
a.property
Run Code Online (Sandbox Code Playgroud)
一种方法通常比其他方法更常用吗?
我在前面的回答中读到异常处理在Python中很便宜所以我们不应该进行预条件检查.
我以前没有听说过这个,但我对Python比较陌生.异常处理意味着动态调用和静态返回,而if语句是静态调用,静态返回.
如何做好检查是坏的,try-except好的,似乎是另一种方式.谁可以给我解释一下这个?
我试图找出确定是否obj可以执行操作的对象的不同方法之间的权衡do_stuff().据我了解,有三种方法可以确定这是否可行:
# Way 1
if isinstance(obj, Foo):
obj.do_stuff()
# Way 2
if hasattr(obj, 'do_stuff'):
obj.do_stuff()
# Way 3
try:
obj.do_stuff()
except:
print 'Do something else'
Run Code Online (Sandbox Code Playgroud)
哪种方法首选(以及为什么)?
do_something.n每次调用函数时,函数属性都会递增.
让我感到困扰的是我在函数do_something.n=0 之外声明了属性.
我回答了使用queue.PriorityQueue的问题,不关心使用"函数属性"进行比较以提供与PriorityQueue一起使用的独特计数器 - MartijnPieters有一个更好的解决方案)
MCVE:
def do_something():
do_something.n += 1
return do_something.n
# need to declare do_something.n before usign it, else
# AttributeError: 'function' object has no attribute 'n'
# on first call of do_something() occures
do_something.n = 0
for _ in range(10):
print(do_something()) # prints 1 to 10
Run Code Online (Sandbox Code Playgroud)
还有什么其他方法来定义函数"内部"的属性,以便在AttributeError: 'function' object has no attribute 'n'忘记它时避免使用它?
从评论中编辑了很多其他方式:
a = SomeClass()
if hasattr(a, 'property'):
a.property
Run Code Online (Sandbox Code Playgroud)
这是检查是否有房产的唯一方法吗?有没有其他方法可以做同样的事情?