2015-11-19 262 views
1

对于我正在处理的项目,我需要将字符串(其中包含ID号(即ID_00000001 ... ID_00002032或类似内容))转换为一类。 我的意思是,已经有存储类有像这样的值:在Python中将字符串转换为类(反之亦然)

class ID_00000001: 
    name = 'Robert Johnson' 
    age = 193 
    facebook_url = 'facebook.com/Robert_johnson' 
    etc. 

我想让它,这样我可以此配置文件和别人比较。我想这样做的方式是比较喜欢的值(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) 

所以,我想我在这方面的问题,是我会怎样能够将字符串转换为一类?

感谢先进!

+0

你为什么不用字典? – ppperry

+7

我有一种感觉,你正在使用有点奇怪的有点.... –

+6

看起来你像混淆类与实例。在进一步学习之前更好地[阅读它](https://docs.python.org/2/tutorial/classes.html) – alfasin

回答

1

您错误地使用了。你有一个类,一个Facebook用户。 这可能是这样的:

class FacebookUser(): 
    def __init__(self, id, name, age, url): 
     self.id = id 
     self.name = name 
     self.age = age 
     self.url = url 

然后,您可以创建实例为每个用户。

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) 

表示类的字符串,您可以添加__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, 
     ) 

这将导致

>>> print(user1) 
FacebookUser(id: 00000001, name: John Doe, age: 27) 

对于其他方式,您可以使用 类方法实现替代构造函数。这些属于一个类的方法,而不是实例。 在这些函数的第一个参数是类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') 
相关问题