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

时间:2022-01-25 23:50:25

In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object?

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

8 个解决方案

#1


63  

How about dir() function before getattr()?

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

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

#2


88  

It's easier to ask forgiveness than to ask permission.

要求宽恕比要求许可更容易。

Don't check to see if a method exists. Don't waste a single line of code on "checking"

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

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

#3


65  

Check if class has such method?

检查班级是否有这样的方法?

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

or

要么

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

You can use self.__class__ instead of Dynamo

您可以使用self .__ class__而不是Dynamo

#4


5  

You can try using 'inspect' module:

您可以尝试使用'inspect'模块:

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

is_method(dyn, 'mymethod')

#5


3  

How about looking it up in dyn.__dict__?

在dyn .__ dict__中查找它怎么样?

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

#6


3  

Maybe like this, assuming all method is callable

也许是这样,假设所有方法都是可调用的

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

#7


1  

If your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:

如果您的方法不在类中,并且您不想运行它并在异常不存在时引发异常:

'mymethod' in globals()

全局中的'mymethod'()

#8


-1  

I think you should look at the inspect package. It allows you to 'wrap' some of the things. When you use the dir method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:

我想你应该看一下检查包。它允许你“包装”一些东西。当你使用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)

The array you get from dir(Two) contains both f_one and f_two and a lot of built in stuff. With inspect you can do this:

你从dir(Two)得到的数组包含f_one和f_two以及很多内置的东西。通过检查,您可以这样做:

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')

This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.

这个例子仍然列出了两个类中的两个方法,但是如果你想限制检查只在特定的类中起作用,那么它需要更多的工作,但这绝对是可能的。

#1


63  

How about dir() function before getattr()?

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

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

#2


88  

It's easier to ask forgiveness than to ask permission.

要求宽恕比要求许可更容易。

Don't check to see if a method exists. Don't waste a single line of code on "checking"

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

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

#3


65  

Check if class has such method?

检查班级是否有这样的方法?

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

or

要么

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

You can use self.__class__ instead of Dynamo

您可以使用self .__ class__而不是Dynamo

#4


5  

You can try using 'inspect' module:

您可以尝试使用'inspect'模块:

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

is_method(dyn, 'mymethod')

#5


3  

How about looking it up in dyn.__dict__?

在dyn .__ dict__中查找它怎么样?

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

#6


3  

Maybe like this, assuming all method is callable

也许是这样,假设所有方法都是可调用的

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

#7


1  

If your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:

如果您的方法不在类中,并且您不想运行它并在异常不存在时引发异常:

'mymethod' in globals()

全局中的'mymethod'()

#8


-1  

I think you should look at the inspect package. It allows you to 'wrap' some of the things. When you use the dir method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:

我想你应该看一下检查包。它允许你“包装”一些东西。当你使用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)

The array you get from dir(Two) contains both f_one and f_two and a lot of built in stuff. With inspect you can do this:

你从dir(Two)得到的数组包含f_one和f_two以及很多内置的东西。通过检查,您可以这样做:

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')

This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.

这个例子仍然列出了两个类中的两个方法,但是如果你想限制检查只在特定的类中起作用,那么它需要更多的工作,但这绝对是可能的。