提问人:jaried 提问时间:6/22/2021 最后编辑:jaried 更新时间:6/23/2021 访问量:66
如何批量生成类实例的属性?
How to generate properties of instances of classes in batches?
问:
我有一个名为 的类。我想在生成 .MyClass
attributes
k_10sec
k_1d
instance
batches
instances
class
如何修改代码?
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
答:
1赞
chepner
6/22/2021
#1
你不需要 ;这是内置作用域中的一个函数,用于为全局变量提供接口。只需使用常规globals
dict
dict
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
最后,我将这两种方法结合起来,并将它们一起使用。
上一个:变量方法的变量属性
评论
self.a = list(range(100))
.为什么需要 100 个单独的属性?