在函数中__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
Run Code Online (Sandbox Code Playgroud)
S.L*_*ott 103
请求宽恕比要求许可更容易.
不要检查方法是否存在.不要在"检查"上浪费一行代码
try:
dyn.mymethod() # How to check whether this exists or not
# Method exists and was used.
except AttributeError:
# Method does not exist; What now?
Run Code Online (Sandbox Code Playgroud)
ser*_*yPS 94
检查班级是否有这样的方法?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
Run Code Online (Sandbox Code Playgroud)
要么
hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
Run Code Online (Sandbox Code Playgroud)
你可以用self.__class__
而不是Dynamo
Mic*_*jer 78
dir()
以前的功能怎么样getattr()
?
>>> "mymethod" in dir(dyn)
True
Run Code Online (Sandbox Code Playgroud)
Shi*_*hah 18
我使用以下实用程序功能。它适用于 lambda、类方法以及实例方法。
实用方法
def has_method(o, name):
return callable(getattr(o, name, None))
Run Code Online (Sandbox Code Playgroud)
示例用法
让我们定义测试类
class MyTest:
b = 'hello'
f = lambda x: x
@classmethod
def fs():
pass
def fi(self):
pass
Run Code Online (Sandbox Code Playgroud)
现在你可以试试,
>>> 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
Run Code Online (Sandbox Code Playgroud)
小智 10
您可以尝试使用'inspect'模块:
import inspect
def is_method(obj, name):
return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))
is_method(dyn, 'mymethod')
Run Code Online (Sandbox Code Playgroud)