如何检查Python中方法是否存在?
在函数 __getattr__()
中,如果找不到你提到的变量,就会报错。那么我该怎么检查一个对象里是否存在某个变量或方法呢?
import string
import logging
class Dynamo:
def __init__(self,x):
print "In Init def"
self.x=x
def __repr__(self):
print self.x
def __str__(self):
print self.x
def __int__(self):
print "In Init def"
def __getattr__(self, key):
print "In getattr"
if key == 'color':
return 'PapayaWhip'
else:
raise AttributeError
dyn = Dynamo('1')
print dyn.color
dyn.color = 'LemonChiffon'
print dyn.color
dyn.__int__()
dyn.mymethod() //How to check whether this exist or not
11 个回答
120
问别人原谅比先征求同意要简单。
不要去检查一个方法是否存在。不要在“检查”上浪费一行代码。
try:
dyn.mymethod() # How to check whether this exists or not
# Method exists and was used.
except AttributeError:
# Method does not exist; What now?
152
怎么检查一个类里有没有某个方法呢?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
你可以用 self.__class__
来代替 Dynamo
111
在使用 getattr()
之前,使用 dir()
函数怎么样?
>>> "mymethod" in dir(dyn)
True