可以用自定义方法创建一个新的python对象吗?

2024-04-26 23:49:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个类,表示流行病模拟。所以在很多情况下,我有一个“S”,“I”和可能的“R”状态(易感,感染,恢复)。所以我在课堂上得到了一个粗略的方法:

def S(self):
    return data['S']

所以我可以用foo.S访问数据 但也许我在看一些其他的模拟,其中我有其他的状态(假设‘E’也是一个状态(exposed))。我希望能够通过类似的方法自动获取其他数据:foo.E。我希望能够在不必更改类本身的情况下收集任何特定的状态。你知道吗

所以我在寻找一种方法来修改__init__MyClass,这样我就可以定义

foo = MyClass(status_list = ('S', 'I', 'E', 'R', 'someotherstatus'))

然后我就可以自动访问foo.someotherstatus。根据我目前的理解,唯一的方法是进入MyClass的代码并显式定义一个方法someotherstatus,该方法将返回data['someotherstatus']。你知道吗


Tags: 数据方法selfdatareturn定义foo状态
2条回答

IIUC,尝试使用setattr

import pandas as pd

data = pd.DataFrame(columns = ['S', 'I', 'E', 'R', 'someotherstatus'])

class MyClass:
    def __init__(self, status_list):
        for i in status_list:
            setattr(self, i, data[i])

foo = MyClass(status_list = ('S', 'I', 'E', 'R', 'someotherstatus'))
foo.S

输出:

Series([], Name: S, dtype: object)

也许这会给你一些想法:

class MyClass:

    def get_status(self, status, other_param=None):
        if other_param:
            return self.data[status] + other_param
        else:
            return self.data[status]

    def __init__(self):
        self.data = {
            'S': 1,
            'someotherstatus': 2,
        }

        # without other params
        setattr(self, 'someotherstatus', self.get_status('someotherstatus'))

        # with an other param
        setattr(self, 'someotherstatus_with_param', lambda other_param: self.get_status('someotherstatus', other_param))

obj = MyClass()
print(obj.someotherstatus)  # 2
print(obj.someotherstatus_with_param(2)) # 4

相关问题 更多 >