Access To Instance Variable, But Not Instance Method In Python
Solution 1:
You seem to be asking "how do I take the string 'inst1' and make a variable called 'inst1'".
The answer is that you don't want to do that. Instead, create a dictionary or list mapping your strings to the objects in question. See this question for some examples.
(If that's not what you're asking please clarify your question.)
Solution 2:
Not that I have any idea what you are really trying to do, to address your specific code, a list is only a collection of values. What you are treating it like is a dict, which is an association between a key and value.
To make your example work, you would use a dict:
classInstanceNames():
def__init__(self):
self.names = {'inst1': None, 'inst2': None, 'inst3': None}
This will now allow the following expression to succeed:
instance_names.names[x] = DoSomething()
... Because names
is now a dict and you are accessing a key and assigning it a value.
Again, I make the disclaimer that I have no idea what this code is trying to do...have the feeling it is probably not good... but not taking the angle of judging it.
Solution 3:
instance_names.names
is a list which requires numbers as indices. In fact, the TypeError you posted says the same thing.
However, you want to set an element using a string in instance_names.names[x]
- where x
is a string. Lists don't allow this, you need to use a dictionary for that.
There are several ways to solve your problem:
You can use a dictionary for instance_names.names in the first place. Then, however, you must use a reserved object such as
None
as a placeholder for instances that haven't been created yet: ´self.names = {'inst1': None, 'inst2': None, 'inst3': None}, and you must iterate through the keys of the dictionary:
for x in instance_names.names.keys():`You can use a separate dictionary for the instances and set its content in the loop:
self.instances = {}
.instance_names.instances[x] = ...
For further reading about Python's data types, I reccomend Dive Into Python.
Solution 4:
You can use type
to create classes dynamically:
type_names = ["Class1", "Class2", "Class3"]
storage = {}
for t in type_names:
storage[t] = type(t, (object, ), {"your": "instance", "attributes": "here"})
for type_name in storage:
print type_name, "=>", storage[type_name]
Alternately, you can used collections.namedtuple
to generate lightweight classes if all you really need is a bunch of attributes.
What you currently have is creating three instances of the DoSomething
class and replacing the string values (which you don't use) in the InstanceNames
class' names
attribute with these three instances of DoSomething
.
Solution 5:
What does it mean or x
?
self.names
doesn't exists in scope, use instance_names.names
instead.
Post a Comment for "Access To Instance Variable, But Not Instance Method In Python"