如何检查Python中是否存在方法?

2024-05-14 05:38:09 发布

您现在位置: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

Tags: 方法key函数inimportselfinitdef
3条回答

请求原谅比请求允许容易。

不要检查方法是否存在。不要在“检查”上浪费一行代码

try:
    dyn.mymethod() # How to check whether this exists or not
    # Method exists and was used.  
except AttributeError:
    # Method does not exist; What now?

检查类是否有这样的方法?

hasattr(Dynamo, key) and callable(getattr(Dynamo, key))

或者

hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))

您可以使用self.__class__而不是Dynamo

getattr()之前dir()函数怎么样?

>>> "mymethod" in dir(dyn)
True

相关问题 更多 >