python - 动态定义类中的方法

标签 python python-3.x

我尝试根据对象创建期间给出的参数在类中动态定义函数。我尝试了一些想法(下面的代码),但它们都无效。也许这是不可能的。我想这样做是因为我会在蒙特卡洛模拟中经常调用 _exec 方法。

我的第一个失败的想法:

class Test_Class_1():
def __init__(self, a = None):
    if a:
        self.a = a

if hasattr(self, 'a'):    #self is undefined.
    def _exec(self):
        print(self.a)
else:
    def _exec():
        print('no a')

我的第二个失败的想法:

class Test_Class_2():
def __init__(self, a = None):
    if a:
        self.a = a

try self.a:           #this is invalid syntax
    def _exec(self):
        print(self.a)
except:
    def _exec():
        print('no a')

我当然可以创建不同的类来实现这一目标,但我宁愿希望一个类具有更容易理解的代码结构(更短)。

感谢您的想法!

最佳答案

您可以覆盖 __setattr__()动态更新 _exec() 的方法方法取决于属性 a 的值。 _exec() 的两种不同实现作为类中的方法提供,每当修改属性时就会选择适当的方法。

同时覆盖__delattr__如果使用 del 删除该属性.

class TestClass:
    def __init__(self, a=None):
        self.a = a

    def _exec_a(self):
        print(self.a)

    def _exec_no_a(self):
        print('no a')

    def __setattr__(self, name, value):
#        print('__setattr__():', name, value)
        super().__setattr__(name, value)
        if name == 'a':
            if value is not None:
                self._exec = self._exec_a
            else:
                del self.a

    def __delattr__(self, name):
#        print('__delattr__():', name)
        super().__delattr__(name)
        if name == 'a':
            self._exec = self._exec_no_a

像这样使用它:

>>> x = TestClass()
>>> x.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'TestClass' object has no attribute 'a'

>>> x._exec()
no a
>>> x.a = 123
>>> x._exec()
123
>>> x.a = 'hello'
>>> x._exec()
hello

>>> x.a = None
>>> x.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'TestClass' object has no attribute 'a'
>>> x._exec()
no a
>>> x.a = 500
>>> x._exec()
500
>>> del x.a
>>> x._exec()
no a
>>> x.a = True
>>> x._exec()
True

>>> x = TestClass(a='xyz')
>>> x._exec()
xyz
>>> del x.a
>>> x._exec()
no a

关于python - 动态定义类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42948487/

相关文章:

python - 如果另一个表中存在一行,则添加 bool 字段?

python - Kivy Ios ./toolchain.py 构建 kivy 不工作

javascript - 将 javascript 变量链接到 Flask

python - 如何导入两个同名的库

python-3.x - 如何通过匹配 Pandas 中两个不同数据帧中的列来更新一个数据帧的列

python - 在 pytest 中,如何访问传递给测试的参数?

python - 通过在 Pandas 的另一列中添加新值来扩展 Timeindex。

python - 尝试注释哈希变量时,“ABCMeta”对象不可下标

python-3.x - 在 selenium python 中处理 PopUp

python-3.x - python : Unable to import TA-lib while it shows in the pip list