简体   繁体   English

将字符串转换为 class 变量名

[英]Turn a String into class variable name

My problem is the following: I've created, in Python, a class let's imagine it is a character with stats, level etc...我的问题如下:我在 Python 中创建了一个 class 让我们想象它是一个具有统计数据、级别等的角色......

I've also created a dictionary in which are lists all the character name and stats, the key of the dictionary being the name of the character.我还创建了一个字典,其中列出了所有字符名称和统计信息,字典的键是字符的名称。

I want to create a function that takes in argument the dictionary and that create the characters as an instance of my class.我想创建一个 function,它接受字典参数并将字符创建为我的 class 的实例。 The problem is that i don't know how to give the character name to my variable, i only have the string corresponding to his name by collecting the key.问题是我不知道如何将字符名称赋予我的变量,我只有通过收集密钥得到与他的名字相对应的字符串。

Example:例子:

class Character():
       def __init__(self,Name,Age):
                self.Nom=Name
                self.Age=Age


List_Character= {"Roger" : 36, "Kimberley" : 98} 


How can I create a function that takes List_Character and return two instance of Character which variable name are Roger and Kimberley?如何创建一个 function,它采用 List_Character 并返回两个变量名为 Roger 和 Kimberley 的 Character 实例?

Try the following:尝试以下操作:

class Character():
       def __init__(self,Name,Age):
                self.Nom=Name
                self.Age=Age
                
       def __repr__(self):
           return f"{self.__class__.__name__}(Name={self.Nom}, Age={self.Age})"


List_Character= {"Roger" : 36, "Kimberley" : 98}

def create_instance(cls, params: dict):
    ret = ()
    for k,v in params.items():
        globals()[k] = cls(k, v)
        ret = ret + (globals()[k],)
    return ret

>>> create_instance(Character, List_Character)
(Character(Name=Roger, Age=36), Character(Name=Kimberley, Age=98))

>>> Roger
Character(Name=Roger, Age=36)

>>> Kimberley
Character(Name=Kimberley, Age=98)

While the __repr__ method is not strictly necessary, the code would work all the same without it, it just gives better representations.虽然__repr__方法不是绝对必要的,但没有它,代码仍然可以工作,它只是提供了更好的表示。

The function can be shortened/optimized using itertools.starmap : function 可以使用itertools.starmap缩短/优化:

from itertools import starmap
def create_instance(cls, params: dict):
    keys, vals = params.keys(), tuple(starmap(cls, params.items()))
    globals().update(dict(zip(keys, vals)))
    return vals

All you need to do is to iterate over your dict and create new characters from them, append them to a list and return this list:您需要做的就是遍历您的 dict 并从中创建新字符,append 将它们放入一个列表并返回此列表:

class Character():
       def __init__(self,Name,Age):
                self.Nom=Name
                self.Age=Age


List_Character= {"Roger" : 36, "Kimberley" : 98}

def create_characters(char_dict):
    return_list = []
    for k,v in char_dict.items():
        return_list.append(Character(k,v))
    return return_list

print(create_characters(List_Character)[0].Nom, create_characters(List_Character)[0].Age)

returns:返回:

Roger 36

I assumed by "return two instances" you meant for example a list with all instances in there, right?我假设“返回两个实例”是指例如一个包含所有实例的列表,对吗? Since I guess you don't only want to have it for 2 instances, but rather as many as there are in the dict you use as input.因为我猜您不仅希望将其用于 2 个实例,而且还希望将其用作输入的 dict 中的数量。

#Edit: If you want to access the characters by their name you can use a dict for that: #Edit:如果您想按名称访问字符,您可以使用 dict :

def create_characters(char_dict):
    return_dict = dict()
    for k,v in char_dict.items():
        return_dict[k] = Character(k,v)
    return return_dict

dict_of_chars = create_characters(List_Character)
print(dict_of_chars["Roger"].Age)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM