python - 如何在 python 类中访问成员函数作为成员变量?

标签 python class

我有一个类:

class Foo():
    def bar(name):
        return something

我想拥有

foo = Foo()
foo.name 

返回与 foo.bar('name') 相同的结果。可能吗?

最佳答案

如果属性不存在,这将自动使用 bar:

class Foo(object):
    def bar(self, name):
        return name
    def bar2(self, attr, value):
        print attr, value
    def __getattr__(self, attr):
        return self.bar(attr)
    def __setattr__(self, attr, value):
        self.bar2(attr, value)
foo = Foo()
print foo.name
foo.name = 'not name'

关于python - 如何在 python 类中访问成员函数作为成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075189/

相关文章:

python - Hadoop(Hive)中是否有类似存储过程/作业的东西

python - 合并并创建具有相同 id 的所有记录的新 JSON 数组

python - 覆盖实例下一个函数

python - 如何递归遍历二叉树?

python - 使用 Beautiful Soup 和 Python 解析元标记

c++ - 类函数更改类cpp中的其他数据

C++ 空类或 typedef

java - 为什么 inc/dec channel 不执行任何操作?

javascript - 使用 John Resig 的 javascript 继承时缓存它

vb.net - .IndexOf 函数在 vb.net 中为类列表返回负数