在函数__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
答案 0 :(得分:100)
请求宽恕比要求许可更容易。
不检查方法是否存在。不要在“检查”上浪费一行代码
try:
dyn.mymethod() # How to check whether this exists or not
# Method exists and was used.
except AttributeError:
# Method does not exist; What now?
答案 1 :(得分:85)
检查班级是否有这样的方法?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
或
hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
您可以使用self.__class__
代替Dynamo
答案 2 :(得分:73)
dir()
之前的getattr()
功能怎么样?
>>> "mymethod" in dir(dyn)
True
答案 3 :(得分:7)
您可以尝试使用'inspect'模块:
import inspect
def is_method(obj, name):
return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))
is_method(dyn, 'mymethod')
答案 4 :(得分:3)
如何在dyn.__dict__
中查找?
try:
method = dyn.__dict__['mymethod']
except KeyError:
print "mymethod not in dyn"
答案 5 :(得分:3)
也许是这样,假设所有方法都是可调用的
app = App(root) # some object call app
att = dir(app) #get attr of the object att #['doc', 'init', 'module', 'button', 'hi_there', 'say_hi']
for i in att:
if callable(getattr(app, i)):
print 'callable:', i
else:
print 'not callable:', i
答案 6 :(得分:1)
如果您的方法不属于某个类,并且您不想运行该方法并且如果它不存在则引发异常:
'mymethod' in globals()
答案 7 :(得分:0)
我使用以下实用程序功能。它适用于lambda,类方法以及实例方法。
实用方法
def has_method(o, name):
return callable(getattr(o, name, None))
用法示例
让我们定义测试类
class MyTest:
b = 'hello'
f = lambda x: x
@classmethod
def fs():
pass
def fi(self):
pass
现在您可以尝试
>>> a = MyTest()
>>> has_method(a, 'b')
False
>>> has_method(a, 'f')
True
>>> has_method(a, 'fs')
True
>>> has_method(a, 'fi')
True
>>> has_method(a, 'not_exist')
False
答案 8 :(得分:0)
适合喜欢简单的人。
class ClassName:
def function_name(self):
return
class_name = ClassName()
print(dir(class_name))
# ['__init__', .... ,'function_name']
answer = 'function_name' in dir(class_name)
print("is'function_name' in class ? >> {answer}")
# is 'function_name' in class ? >> True
答案 9 :(得分:-1)
我认为您应该查看inspect
包。它允许你“包装”一些东西。当您使用dir
方法时,它还列出了内置方法,继承方法和所有其他使冲突成为可能的属性,例如:
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
print dir(Two)
您从dir(Two)
获得的数组包含f_one
和f_two
以及许多内置内容。使用inspect
,您可以执行此操作:
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
import inspect
def testForFunc(func_name):
## Only list attributes that are methods
for name, _ in inspect.getmembers(Two, inspect.ismethod):
if name == func_name:
return True
return False
print testForFunc('f_two')
这个例子仍然列出了两个类中的两个方法,但是如果你想将检查限制为仅在特定类中起作用,则需要更多的工作,但这绝对是可能的。