0

我有一个字符串列表,每个字符串都代表书籍及其一些属性,例如

# each book followed by the price and the name of the genre
book_names = ['love 3 romance',
              'rose 6 drama',
              'flower 7 nice_story']

我想以某种方式为每本书创建一个新对象,并为其创建字符串描述属性的其他部分。

这是我尝试过的(显然,它不起作用):

class Book_Class():
  price=0
  genre=''
  book_content=[]

for i in book_names:
  name=i.split()[0]
  name=Book_Class()
  name.price=i.split()[1]
  name.genre=i.split()[2]

也许有一种简单的方法可以实现我所追求的(请告诉我,因为我对编程还很陌生……)。

4

3 回答 3

7

有几种方法:

  1. 改用字典,在许多情况下就足够了:

    keys = ['name', 'price', 'gender']
    book = { k: v for k, v in zip(keys, i.split()) }
    
  2. 给你的Book类一个有意义的__init__初始化器:

    class Book(object):
        name = ''
        price = 0
        gender = None
    
        def __init__(self, name, price, gender):
            self.name = name
            self.price = price
            self.gender = gender
    

    并将您的解析值传递给它:

    Book(*i.split())
    
  3. 作为最后的手段,您可以使用setattr在现有对象上设置任意属性:

    book = Book()
    for attr, value in zip(keys, i.split()):
        setattr(book, attr, value)
    
于 2012-10-10T11:41:23.270 回答
1

完成相同任务的另一种方法是使用命名元组。

book_names = ['love 3 romance',
              'rose 6 drama',
              'flower 7 nice_story']

from collections import namedtuple
book = namedtuple("Book", "name price genre")

# convert book_names to books
[book(*b.split()) for b in book_names]

Output: [Book(name='love', price='3', genre='romance'),
         Book(name='rose', price='6', genre='drama'),
         Book(name='flower', price='7', genre='nice_story')]

然后您可以按预期访问属性

book1 = [book(*b.split()) for b in book_names][0]
print book1.name, book1.price, book1.genre
Output: ('love', '3', 'romance')

如果你想使用第一个参数作为变量名,你可以这样做:

book = namedtuple("Book", "price genre")
for b in book_names:
    globals()[b.split()[0]] = book(*b.split()[-2:])

# now you can access your books:
love.price 
于 2012-10-10T12:26:20.933 回答
0

Ashwini Chaudhary 给出的答案是使用 globals()

# each book followed by the price and the name of the genre
book_names = ['love 3 romance',
              'rose 6 drama',
              'flower 7 nice_story']
class Book_Class():
  price=0
  genre=''
  book_content=[]
for i in book_names:
  nnn='name'
  globals()[nnn]=i.split()[0]
  name=Book_Class()
  name.price=i.split()[1]
  name.gender=i.split()[2]
于 2012-10-10T12:06:20.317 回答