[英]Converting a String to a Class (and vice versa) in Python
For a project that I am working on, I need to convert a string (which has ID numbers (ie ID_00000001...ID_00002032 or something like that)) into a class. 对于我正在处理的项目,我需要将字符串(具有ID号(即ID_00000001 ... ID_00002032或类似的名称))转换为类。 By that I mean, there is already a class stored that has values like so: 我的意思是,已经存储了一个类,其值如下:
class ID_00000001:
name = 'Robert Johnson'
age = 193
facebook_url = 'facebook.com/Robert_johnson'
etc.
I want to make it so that I can compare this profile to others. 我想这样做,以便可以将此配置文件与其他配置文件进行比较。 The way I was thinking of doing this was comparing values like (psudo): 我想到的方式是比较(psudo)之类的值:
current_profile_str = 'ID_00000001'
for i in range(len(all_IDs)):
matches = []
num = *converts number into 8 digit str*
cycle_profile_str = 'ID_' + num
*convert current_profile and cycle_profile to class*
if (current_profile.age == cycle_profile.age):
matches.append(cycle_profile_str)
So the question that I suppose I have in this context, is how would I be able to convert a string to a class? 因此,我想在这种情况下遇到的问题是,如何将字符串转换为类?
You are using classes wrongly. 您错误地使用了类 。 You have one class, a facebook user. 您只有一个班级,一个facebook用户。 This could look like this: 可能看起来像这样:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
You can then create instances for each user. 然后,您可以为每个用户创建实例 。
user1 = FacebookUser(1, 'John Doe', 27, 'facebook.com/john_doe')
user2 = FacebookUser(3, 'Jane Doe', 92, 'facebook.com/jane_doe')
print(user1.age == user2.age)
To represent a class as a string, you can add the __repr__
magic function to the class: 要将一个类表示为字符串,可以向__repr__
添加__repr__
魔术函数:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
def __repr__(self):
return 'FacebookUser(id: {:08d}, name: {}, age: {})'.format(
self.id,
self.name,
self.age,
)
This will result in 这将导致
>>> print(user1)
FacebookUser(id: 00000001, name: John Doe, age: 27)
For the other way around, you would implement an alternative constructor using a class method. 另一方面,您可以使用类方法实现替代构造函数。 These are methods belonging to a class, not to the instance. 这些是属于类而不是实例的方法。 The first argument in these functions is the class cls
, not the instance self
: 这些函数中的第一个参数是cls
类,而不是实例self
:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
def __repr__(self):
return 'FacebookUser(id: {:08d}, name: {}, age: {})'.format(
self.id,
self.name,
self.age,
)
@classmethod
def from_string(cls, string):
'''
Create a new instance from a string with format
"id,name,age,url"
'''
_id, name, age, url = string.split(',')
return cls(int(_id), name, int(age), url)
user1 = FacebookUser.from_string('1,John Doe,27,facebook.com/john_doe')
MaxNoe's answer is probably what you're looking for, but anyway... MaxNoe的答案可能是您想要的,但是无论如何...
If you really, actually want to somehow build up a class from a sequence of strings (For example, to have variables with their names extracted from the string itself, then you might want to look at metaclasses. 如果您确实确实想以某种方式从一系列字符串中构建一个类(例如,要使变量及其名称从字符串本身中提取出来,那么您可能希望查看元类。
http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.