如何检查Python中是否存在方法? [英] How to check whether a method exists in Python?

查看:114
本文介绍了如何检查Python中是否存在方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在功能__getattr__()中,如果找不到引用的变量,则将给出错误.如何检查变量或方法是否作为对象的一部分存在?

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?

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

推荐答案

getattr()之前的dir()函数如何?

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

这篇关于如何检查Python中是否存在方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆