在函数__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
最佳答案
dir()
之前的getattr()
函数如何?
>>> "mymethod" in dir(dyn)
True
关于python - 如何检查Python中是否存在方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7580532/