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

2024-05-15 21:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

客户是一个类。

在我的测试中,这个循环运行两次,将“objectname”打印为Customer1和Customer2,但是创建了两个对象,但是这些对象被称为“objectname”(它覆盖每个循环),而不是两个唯一的对象Customer1或Customer2。

它只是不在变量中分配字符串(customer1,2),而只是变量名。

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

当然,这必须一直做,谢谢你的帮助提前。


Tags: 对象字符串namein名称forobjectcustomer
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()

你需要的是一本字典:

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

动态生成变量名通常没有那么有用。我肯定会建议像尼克拉斯的答案,但如果你知道这是你想要的,这里是你如何做到的:

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')

这样做时,需要确保customername是一个valid Python identifier

相关问题 更多 >