Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a variable to an object name?

Tags:

python

Tried the following, where "objectname" contains a string name, to be assigned on creation of an object.

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

Where Customer is a class.

In my test, this loop runs twice printing "objectname" as Customer1 and Customer2, yet creates 2 objects, but the objects are called "objectname" (it overwrites each loop), opposed to the 2 unique objects Customer1 or Customer2.

Its simply not assigning strings(customer1,2) inside the variable, but purely the variables name.

I've tried assigning strings to the object name, but that gives a syntax error

Surely this must be done all the time, thanks for your help in advance.

like image 825
user1123221 Avatar asked Oct 26 '25 01:10

user1123221


2 Answers

Instead of using a new variable for each customer you could store your object in a Python dictionary:

d = dict()

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

print d

An example of objects stored in dictionaries

I just could'nt help my self writting some code (more than I set out to do). It's like addictive. Anyway, I would'nt use objects for this kind of work. I probably would use a sqlite database (could be saved in memory if you want). But this piece of code show you (hopefully) how you can use dictionaries to save objects with customer data in:

# 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()
like image 170
Niclas Nilsson Avatar answered Oct 28 '25 14:10

Niclas Nilsson


It is generally not that useful to have dynamically generated variable names. I would definitely suggest something like Niclas' answer instead, but if you know this is what you want here is how you can do it:

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

This will result in the variables Customer1 and Customer2 being added to the innermost scope, exactly like if you had executed the following lines:

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

When doing it this way you need to make sure that customername is a valid Python identifier.

like image 33
Andrew Clark Avatar answered Oct 28 '25 15:10

Andrew Clark