如何获取class实例变量,python
How to get class instance variables, python
我想获取__init__
个参数的名称,并在代码运行时修改它们。我的 class 看起来像这样:
class Sample:
def __init__ (self,indicators:dict):
self.names = []
self.returns = 0.0
for k,v in indicators.items():
setattr(self, k, v)
self.names.append(k)
这个class的输入是从列表中随机选择的项目;然后我将这些随机项目分配给具有整数值的字典。
indicatorsList =["SMA", "WMA", "EMA", "STOCHASTIC", "MACD", "HIGHEST_HIGH",
"HIGHEST_LOW", "HIGHEST_CLOSE", "LOWEST_HIGH", "LOWEST_LOW",
"LOWEST_CLOSE", "ATR", "LINGRES", "RSI", "WRSI", "ROC",
"DAY", "MONTH"]
# initializing the value of n
n = random.randint(2,int(math.ceil(len(indicatorsList)/2)))
randomIndList = n * [None]
for i in range(n):
choice = random.choice(indicatorsList)
randomIndList[i] = choice
...
...
sample = Sample(randDict)
问题是,我不知道__init__
中这些参数的名称,以后需要修改它们,比如这样:
sample.sma = random.randint(0, maxVal)
但我不知道该对象是否具有 sma
、ema
或任何其他属性,因为它们是随机分配的。
首先,这段代码:
sample.sma = random.randint(0, maxVal)
将工作,即使sample
没有sma
属性。它将创建一个。自己试试看。
但是正如您在评论中指定的那样,您只想修改已经存在的属性,这在这种情况下无济于事。
你可以做什么,用你现有的class定义,是循环遍历你已经定义的names
属性。
for name in sample.names:
setattr(sample, name, random.randint(0, maxVal))
不过,你在这里基本上是重新发明了一个字典,那么为什么不重新定义你的class直接使用字典呢?
class Sample:
def __init__(self, indicators:dict):
self.indicators = indicators
现在您不再需要动态 setattr
或 getattr
查找。它们只是键和值:
for key in sample.indicators:
sample.indicators[key] = random.randint(0, maxVal)
(这也意味着您不需要单独的 names
属性。)
我想获取__init__
个参数的名称,并在代码运行时修改它们。我的 class 看起来像这样:
class Sample:
def __init__ (self,indicators:dict):
self.names = []
self.returns = 0.0
for k,v in indicators.items():
setattr(self, k, v)
self.names.append(k)
这个class的输入是从列表中随机选择的项目;然后我将这些随机项目分配给具有整数值的字典。
indicatorsList =["SMA", "WMA", "EMA", "STOCHASTIC", "MACD", "HIGHEST_HIGH",
"HIGHEST_LOW", "HIGHEST_CLOSE", "LOWEST_HIGH", "LOWEST_LOW",
"LOWEST_CLOSE", "ATR", "LINGRES", "RSI", "WRSI", "ROC",
"DAY", "MONTH"]
# initializing the value of n
n = random.randint(2,int(math.ceil(len(indicatorsList)/2)))
randomIndList = n * [None]
for i in range(n):
choice = random.choice(indicatorsList)
randomIndList[i] = choice
...
...
sample = Sample(randDict)
问题是,我不知道__init__
中这些参数的名称,以后需要修改它们,比如这样:
sample.sma = random.randint(0, maxVal)
但我不知道该对象是否具有 sma
、ema
或任何其他属性,因为它们是随机分配的。
首先,这段代码:
sample.sma = random.randint(0, maxVal)
将工作,即使sample
没有sma
属性。它将创建一个。自己试试看。
但是正如您在评论中指定的那样,您只想修改已经存在的属性,这在这种情况下无济于事。
你可以做什么,用你现有的class定义,是循环遍历你已经定义的names
属性。
for name in sample.names:
setattr(sample, name, random.randint(0, maxVal))
不过,你在这里基本上是重新发明了一个字典,那么为什么不重新定义你的class直接使用字典呢?
class Sample:
def __init__(self, indicators:dict):
self.indicators = indicators
现在您不再需要动态 setattr
或 getattr
查找。它们只是键和值:
for key in sample.indicators:
sample.indicators[key] = random.randint(0, maxVal)
(这也意味着您不需要单独的 names
属性。)