python - 使用 __getattr__ 防止调用不正确的方法

标签 python

我试图防止实例在调用实例不存在的方法时抛出异常。我尝试了以下方法:

class myClass(object):
    def __init__(self):
        pass
    def __getattr__(self,name):
        print "Warning - method {0} does not exist for this instance".format(name)

o = myClass()
var = o.someNonExistantFunction()

问题是我收到以下错误:

TypeError: 'NoneType' object is not callable

我想确保做的两件事是:

  1. 返回 None 因为我的代码可以处理设置为 None 的变量
  2. 执行功能(打印警告消息)

最干净的方法是什么?

最佳答案

返回一个什么都不做的函数?

一些事情:首先你可能想使用 __getattr__ 而不是 __getattribute__
__getattr__ 在运行时在层次结构中找不到任何具有该名称的内容时被调用,__getattribute__ 每次都会被调用。

class Test(object):
    def __getattr__(self,key):
        def placeholder(*args, **kwargs):
            print "Warning - method '%s' does not exist for this instance"%key
        return placeholder

关于python - 使用 __getattr__ 防止调用不正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813042/

相关文章:

python - 设置空闲线程/信令线程

python - 导入前 PyCharm 打印?

python - 准备从 Python 2.x 转换到 3.x

python - PIL - 量化表的数量无效。应在 2 到 4 之间

python - 为什么我的程序使用系统 cpu 时间?

python请求-在HTTP请求中POST多部分/表单数据没有文件名

python - key 错误 : Timestamp

Python:无法 pickle 模块对象错误

python - 在列表中重复列表 X 次

python - 如何根据查找数据框检查由字符串列表组成的数据框并执行计算?