如何将变量分配给对象名称?

时间:2011-12-30 17:50:16

标签: python

尝试以下操作,其中“objectname”包含要在创建对象时分配的字符串名称。

for record in result:
    objectname = 'Customer' + str(record[0])
    print objectname
    customername = str(record[1])
    objectname = Customer(customername)

客户是一个类。

在我的测试中,此循环运行两次打印“objectname”作为Customer1和Customer2,但创建了2个对象,但对象称为“objectname”(它覆盖每个循环),与2个唯一对象Customer1或Customer2相对。

它根本不是在变量中分配字符串(customer1,2),而是纯粹的变量名称。

我已尝试将字符串分配给对象名称,但这会产生语法错误

肯定必须一直这样做,谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

您可以将对象存储在Python字典中,而不是为每个客户使用新变量:

d = dict()

for record in result:
    objectname = 'Customer' + str(record[0])
    customername = str(record[1])
    d[objectname] = Customer(customername)

print d

存储在词典

中的对象示例

我无法帮助自己编写一些代码(比我开始做的更多)。这就像上瘾。无论如何,我不会使用对象进行这种工作。我可能会使用sqlite数据库(如果你愿意,可以保存在内存中)。但是这段代码向您展示了(希望如何)使用词典来保存带有客户数据的对象:

# Initiate customer dictionary
customers = dict()

class Customer:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname
        self.address = None
        self.zip = None
        self.state = None
        self.city = None
        self.phone = None

    def add_address(self, address, zp, state, city):
        self.address = address
        self.zip = zp
        self.state = state
        self.city = city

    def add_phone(self, number):
        self.phone = number


# Observe that these functions are not belonging to the class.    
def _print_layout(object):
        print object.fname, object.lname
        print '==========================='
        print 'ADDRESS:'
        print object.address
        print object.zip
        print object.state
        print object.city
        print '\nPHONE:'
        print object.phone
        print '\n'

def print_customer(customer_name):
    _print_layout(customers[customer_name])

def print_customers():
    for customer_name in customers.iterkeys():
        _print_layout(customers[customer_name])

if __name__ == '__main__':
    # Add some customers to dictionary:
    customers['Steve'] = Customer('Steve', 'Jobs')
    customers['Niclas'] = Customer('Niclas', 'Nilsson')
    # Add some more data
    customers['Niclas'].add_address('Some road', '12312', 'WeDon\'tHaveStates', 'Hultsfred')
    customers['Steve'].add_phone('123-543 234')

    # Search one customer and print him
    print 'Here are one customer searched:'
    print 'ooooooooooooooooooooooooooooooo'
    print_customer('Niclas')

    # Print all the customers nicely
    print '\n\nHere are all customers'
    print 'oooooooooooooooooooooo'
    print_customers()

答案 1 :(得分:2)

动态生成变量名通常没那么有用。我肯定会建议像Niclas'相反,但如果您知道这就是您想要的,那么您将如何做到这一点:

for record in result:
    objectname = 'Customer' + str(record[0])
    print objectname
    customername = str(record[1])
    exec '%s = Customer(%r)' % (customername, customername)

这将导致变量Customer1Customer2被添加到最里面的范围,就像您执行了以下行一样:

Customer1 = Customer('Customer1')
Customer2 = Customer('Customer2')

这样做时,您需要确保customernamevalid Python identifier

答案 2 :(得分:1)

你需要的是一本字典:

customers = {}
for record in result:
    objectname = 'Customer' + str(record[0])
    customers[customername] = Customer(str(record[1]))  #assignment to dictionary