簡體   English   中英

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

[英]How to check whether a method exists in 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

檢查類是否有這樣的方法?

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

要么

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

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

請求寬恕比請求許可容易。

不要檢查方法是否存在。 不要在“檢查”上浪費一行代碼

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

getattr()之前的dir()函數怎么樣?

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

我使用以下實用程序功能。 它適用於 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                                                          

您可以嘗試使用“檢查”模塊:

import inspect
def is_method(obj, name):
    return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))

is_method(dyn, 'mymethod')

dyn.__dict__如何?

try:
    method = dyn.__dict__['mymethod']
except KeyError:
    print "mymethod not in dyn"

也許像這樣,假設所有方法都是可調用的

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

如果您的方法在類之外並且您不想運行它並在它不存在時引發異常:

'mymethod' in globals()

對於喜歡簡單的人。


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

我認為您應該查看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_onef_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')

此示例仍然列出了兩個類中的兩種方法,但是如果您想將檢查限制為僅在特定類中起作用,則需要做更多的工作,但這絕對是可能的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM