如何批量生成类实例的属性?

How to generate properties of instances of classes in batches?

提问人:jaried 提问时间:6/22/2021 最后编辑:jaried 更新时间:6/23/2021 访问量:66

问:

我有一个名为 的类。我想在生成 .MyClassattributesk_10seck_1dinstancebatchesinstancesclass

如何修改代码?

bars = ['10sec', '1min', '5min', '30min', '1d']


class MyClass:
    def __init__(self):
        for bar in bars:
            if bar.endswith('sec'):
                duration_seconds = int(bar[:-3])
            elif bar.endswith('min'):
                duration_seconds = int(bar[:-3] * 60)
            elif bar.endswith('d'):
                duration_seconds = int(bar[:-1] * 60 * 60 * 24)
            self.globals()[f'k_{bar}'] = duration_seconds


s1 = MyClass()
for bar in bars:
    print(s1.[f'k_{bar}'])

我的预期结果:

10
60
300
1800
86400

最后,我将这两种方法结合起来并一起使用。

import re


def parse_time(bar='', secs=0):
    if bar != '':
        bar = re.split('(\d+)', bar)
        if bar[2] in ('sec', 's'):
            secs = int(bar[1])
        elif bar[2] == 'min':
            secs = int(bar[1]) * 60
        elif bar[2] in ('hour', 'h'):
            secs = int(bar[1]) * 60 * 60
        elif bar[2] in ('d', 'day', 'D'):
            secs = int(bar[1]) * 60 * 60 * 24
        else:
            pass
        return secs
    elif secs != 0:
        if secs % (60 * 60 * 24) == 0:
            bar = str(secs // (60 * 60 * 24)) + 'day'
        elif secs % (60 * 60) == 0:
            bar = str(secs // (60 * 60)) + 'hour'
        elif secs % 60 == 0:
            bar = str(secs // 60) + 'min'
        else:
            bar = str(secs) + 'sec'
        return bar
    else:
        pass


class MyClass:
    def __init__(self, bars):
        self.d = {f'k_{bar}': parse_time(bar=bar) for bar in bars}


if __name__ == '__main__':
    bars = ['10sec', '1min', '5min', '30min', '1d']
    s1 = MyClass(bars)
    pass
python 类 变量变量

评论

2赞 chepner 6/22/2021
self.a = list(range(100)).为什么需要 100 个单独的属性?
2赞 quamrana 6/22/2021
这回答了你的问题吗?如何创建变量变量?
1赞 Eric McLachlan 6/22/2021
使用字典来存储使用“变量名称”作为键的值。
0赞 jaried 6/22/2021
@chepner 可以使用大约 6-9 个属性。
0赞 jaried 6/22/2021
@quamrana我已经实现了变量变量的使用,但我还没有找到在类中使用变量变量的方法。

答:

1赞 chepner 6/22/2021 #1

你不需要 ;这是内置作用域中的一个函数,用于为全局变量提供接口。只需使用常规globalsdictdict

class MyClass:
    def __init__(self, bars):
        self.d = {}
        for bar in bars:
            if bar.endswith('sec'):
                duration_seconds = int(bar[:-3])
            elif bar.endswith('min'):
                duration_seconds = int(bar[:-3]) * 60
            elif bar.endswith('d'):
                duration_seconds = int(bar[:-1]) * 60 * 60 * 24
            self.d[f'k_{bar}'] = duration_seconds

s1 = MyClass(['10sec', '1min', '5min', '30min', '1d'])
for bar in s1.d:
    print(s1.d[bar])

不过,我会将时间字符串转换为秒数的逻辑移动到单独的函数中:

def parse_time(s):
    if s.endswith('sec'):
        return int(s[:-3])
    elif s.endswith('min'):
        return int(s[:-3]) * 60
    elif s.endswith('d'):
        return int(s[:-1]) * 60 * 60 * 24


class MyClass:
    def __init__(self, bars):
        self.d = {f'k_{bar}': parse_time(bar) for bar in bars}
1赞 ShiraStar 6/22/2021 #2

我写了一个非常简单的解决方案,希望这是你的意图

import re

bars = ['10sec', '1min', '5min', '30min', '1d']

class MyClass:
    def duration_seconds(self, bar):
        bar = re.split('(\d+)', bar)
        if bar[2] == 'sec':
            secs = int(bar[1])
        elif bar[2] == 'min':
            secs = int(bar[1]) * 60
        elif bar[2] == 'd':
            secs = int(bar[1]) * 60 * 60 * 24
        return secs


s1 = MyClass()
for bar in bars:
    print(s1.duration_seconds('k_{0}'.format(bar)))

评论

0赞 jaried 6/23/2021
最后,我将这两种方法结合起来,并将它们一起使用。