如何将变量赋值为对象名称?

4 投票
3 回答
17759 浏览
提问于 2025-04-17 09:16

我尝试了以下代码,其中“objectname”包含一个字符串名称,用于在创建对象时进行赋值。

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

这里的 Customer 是一个类。

在我的测试中,这个循环运行了两次,打印出“objectname”为 Customer1 和 Customer2,但实际上只创建了两个对象,而这两个对象的名字都是“objectname”(每次循环都会覆盖之前的),而不是两个独特的对象 Customer1 或 Customer2。

这只是没有在变量中赋值字符串(customer1,2),而是纯粹使用了变量的名字。

我尝试将字符串赋值给对象名称,但那样会出现语法错误。

这肯定是经常需要做的事情,提前感谢你的帮助。

3 个回答

1

你需要的是一个字典:

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

一般来说,动态生成变量名并不是特别有用。我更推荐像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')

用这种方式时,你需要确保 customername 是一个有效的Python标识符

6

与其为每个客户都用一个新的变量,不如把你的对象存储在一个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()

撰写回答