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

Raj*_*eev 65 python methods

在函数中__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)

  • 但也许他真的不想打电话,只是为了检查是否有这种方法(就像我的情况一样)...... (50认同)
  • 请注意,如果`dyn.mymethod()`引发`AttributeError`本身,这将失败. (43认同)
  • 正如@DK所说,这将捕获可能由被检查的方法引发的任何AttributeError,这可能是不合需要的(更不用说在这种情况下它会错误地推断出该方法的缺失). (9认同)
  • 这在很多层面上都是错误的。方法本身可以引发 AttributeError 并且这将被检测为方法不存在!它还会破坏调试器对中断异常的支持。我也确定如果事情处于循环中,这可能会影响性能。最后但未列出我可能不想执行方法,只需验证它是否存在。您应该考虑删除此答案或至少放置所有这些警告,以免天真的人被误导。 (4认同)
  • 原则上很好,Python确实有一个与其他语言不同的"控制流例外"文化.但是,如果您使用的是异常日志记录工具(如Sentry/Raven或New Relic),则必须单独过滤此类异常(如果可能)或生成噪声.我更愿意检查方法是否存在而不是调用它. (2认同)
  • OP问“如何检查Python中是否存在某个方法?” 而不是“我如何执行一个可能不存在的方法?”。你已经回答了另一个问题。 (2认同)

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

  • `None`是不可调用的,所以你可以做`callable(getattr(Dynamo,'mymethod',None))`.我使用了这个答案,因为我的super().mymethod()可以抛出`AttributeError` (19认同)
  • **更简单的版本:** 如果你想检查当前类实例是否有一个属性并且它是可调用的,只需执行以下操作:`if hasattr(self, "work") and callable(self.work)`。这会检查实例是否具有工作属性(可以是变量或函数),然后检查它是否可调用(意味着它是一个函数)。 (5认同)
  • @bszom:在 python shell 中,`help(getattr)` 表示“当给出默认参数时,当属性不存在时返回它;如果没有它,在这种情况下会引发异常。” --(事实上,如果属性丢失,您可以检查 getattr 是否会引发异常)很明显,无论 PyCharm 是什么,它都是错误的。 (2认同)

Mic*_*jer 78

dir()以前的功能怎么样getattr()

>>> "mymethod" in dir(dyn)
True
Run Code Online (Sandbox Code Playgroud)

  • 这不会检查它是方法还是变量 (7认同)

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)

  • 这个答案比其他答案更合适(至少在我看来),因为它不使用通用方法(使用“try”语句),并且每当成员是实际函数时它都会进行检查。很棒的分享! (3认同)

小智 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)