user5474086
user5474086

Reputation:

How can I use the value of a variable in the name of another without using a dictionary in python?

The answer people have already given for using the value of a variable in the assignment of another is:

  1. to create a dictionary and,
  2. use dict[oldVariable] instead of defining a new one

I don't think that works in the context of what I'm trying to do...

I'm trying to define a class for a vector which would take a list as an input and assign an entry in the vector for each element of the list.

My code looks something like this right now:

class vector:

    def __init__(self, entries):
        for dim in range(len(entries)):
            for entry in entries:
                self.dim = entry  #here I want to assign self.1, self.2, etc all the way to however 
                                  #many elements are in entries, but I can't replace self.dim with 
                                  # dict[dim]
    def __str__(self):
        string = []
        for entry in range(1,4):
            string.append(self.entry)
        print(string)

How do I do this?

Upvotes: 1

Views: 58

Answers (2)

Brent Writes Code
Brent Writes Code

Reputation: 19623

If I'm reading your question correctly, I think you're looking for the setattr function (https://docs.python.org/2/library/functions.html#setattr).

If you wanted to name the fields with a particular string value, you could just do this:

class vector:
    def __init__(self, entries):
        for dim in range(len(entries)):
            for entry in entries:
                #self.dim = entry
                setattr(self, str(dict[dim]), dim)

That will result in your object self having attributes named with whatever the values of dict[dim] are and values equal to the dim.

That being said, be aware that an integer value is generally a poor attribute name. You won't be able to do print obj.1 without error. You'd have to do getattr(obj,'1').

I agree with @Ricardo that you are going about this strangely and you should probably rethink how you're structuring this class, but I wanted to directly answer the question in case others land here looking for how to do dynamic naming.

Upvotes: 0

nsx
nsx

Reputation: 705

What you are doing here is a bit strange, since you are using a variable named "dim" in a for, but you do not do anything with that variable. It looks like you want to use a class as if it was an array... why don't you define an array within the class and access it from the outside with the index? v.elements[1] ... and so on?

Example:

class Vector:

    def __init__(self, entries):

        self.elements = []
        for e in entries:
            self.elements.append(self.process(e))

    def __str__(self):

        buff = ''
        for e in self.elements:
            buff += str(e)
        return buff

Hope this helps.

Upvotes: 1

Related Questions