This question already has answers here:
Using a string variable as a variable name [duplicate]
(3 answers)
Closed 6 years ago.
Python 3.4.2 question, I have extensively looked for an answer to this, cannot find it.
I am trying to create python objects (or whatever you would call lists, dicts, and classe/object instantiations) by assigning strings to the definition. Or put differently, I want to use strings on the left hand side of the assign equation.
For instance, if we have a class, and an assignment/instantiation:
class char_info:
def __init__(self):
self.name = 'Joe'
self.mesh = 'Suzanne'
newchar = char_info()
print (newchar.name)
Joe
I would like to use using a string from another source (say a list) as the instantiated name, instead of "newchar". However, I am not sure the syntax. I need to reference this string on the left hand side of the equation. Furthermore, how do I reference this in later code since I wouldn't know the name beforehand, only at runtime?
Obviously this doesn't work:
list = ['Bob', 'Carol', 'Sam']
# list[0] = char_info() #this doesn't work, it would
# try assigning the value of char_info() to the item in [0]
str(list[0]) = char_info() #also doesn't work, obviously
print (str(list[0]) #obviously this is wrong, but how do you reference?
location: :-1
Error: File "\Text", line 2
SyntaxError: can't assign to function call
What I want is to have say, a loop that iterates over a list/dict and uses those strings to instantiate the class. Is there any way to do this? Special syntax I am not aware of?
By the way, this same thing should be the solution to do the same thing with creating list names, dict names, etc. Heck, even something simple like enumerating a variable name or assigning variables out of a list. How do you dynamically define the assignment name?
You can use exec i.e. exec(list[0] + "=char_info()") but this is a bad idea. Using a dictionary is better:
chars = {}
chars[list[0]] = char_info()
What I want is to have say, a loop that iterates over a list/dict and
uses those strings to instantiate the class. Is there any way to do
this?
class char_info:
def __init__(self, name):
self.name = name
list_names = ['Bob', 'Carol', 'Sam']
list_char_info = [char_info(name) for name in list_names]
The above code will instantiate a class for each name in the list of names
Related
This question already has answers here:
Accessing class variables from a list comprehension in the class definition
(8 answers)
Closed 2 years ago.
Basically, why do these work:
class MyClass:
Dict={['A','B','C'][i]:{['a','b','c'][j]:[1,2,3][j] for j in range(3)} for i in range(3)}
and
class MyClass:
Table = ['A','B','C']
Dict={Table[0]:'a',Table[1]:'b',Table[2]:'c'}
but not this one?
class MyClass:
Table = ['A','B','C']
Dict={Table[i]:['a','b','c'][i] for i in range(3)}
I'm trying to consolidate a bunch of arrays, interpolation functions, and solvers by putting them all in classes. Each array contains a number of different properties so I figured the best way to sort this data was through nested dictionaries (Many of the tables aren't complete so I can't use numpy arrays or even lists very effectively because the indices change depending on the line of the data). I've worked out all the other kinks, but for some reason moving it into a class gives me an error:
NameError: name 'Table' is not defined
I'm an engineering student and basically only learned how to use scipy solvers and integrators; everything else is self taught. Don't be afraid to tell me I'm doing everything wrong :)
I think you are trying to do a Dictionary Comprehension, but weird enough, this message error you receive does not make much sense to me.
Anyway, with this implementation it worked just fine for me:
class MyClass:
Table = ['A','B','C']
Dict= {i:j for i,j in zip(Table, ['a','b', 'c'])}
This is a class variable + comprehension scope issue. Table is not defined inside your dictionary comprehension, and in the other definition which uses Table you are not doing a comprehension.
You may want to use __init__ here.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I was wondering if there is a way that you can make a class instance by using concatenation.
(setting a class name like person1, person2, etc... , automatically)
I tried to make a code like:
class ID:
def __init__(self):
self.price = 2000
for i in range(50):
string = person + str(i)
string = ID()
But for some reason it didn't work.
Why can't this be defined this way?
Is this even possible?
usually people use a dictionary for this
people = {}
for i in range(50):
people["person"+str(i)] = ID()
if you are really determined to make a global variable you certainly can... but its a much better idea to use a dictionary
if you really wanted a variable named person1..50 though you could just do as follows
for i in range(50):
globals()['person'+str(i)] = ID()
print(person2)
but your ide and anyone who has to work with your code in the future will not appreciate it
I have a question about how Python knows certain things. For example, when I write
a_list = ["car", "plane"]
print(a)
Python knows that a_list is a list. How does that work? where is it written in the default modules of python?
I want to create an object that works kinda like a list, but when I want to obtain the item in a specific position, I would want to write
object_list[0]
instead of a method like
object_list.obtain_item(0)
And I would want to create an object doing something like
$"car", "plane"$
# like yo do ["car", "plane"] by default
And I can't inherit from list cause it's prohibited in the project I'm working on.
Is this even possible? I was searching here and on the internet, but I can't even put my question in words to search properly.
To answer your first question, that would be a consequence of the implementation of the __getitem__ method.
class Foo():
def __init__(self, x, y):
self.x = x
self.y = y
def __getitem__(self, ind):
if ind == 0:
return self.x
return self.y
x = Foo(1, 2)
print(x[0])
1
print(x[1])
2
Note that this is a very bare implementation, and I haven't used a list because you said you can't use it.
To answer your second question, that would involve making changes to the fundamental syntax and grammar of the language, which you, as an end user of the language, are currently not entitled to do.
Python knows that a_list is a list. How does that work? where is it
written in the default modules of python?
Python interpreter recognize the list literal and then create a list object. The Python list object is part of the "standard types that are built into the interpreter".
I want to create an object that works kind like a list, but when i
want to obtain the item in a specific position, i would want to write
You can do that use object.getitem(self, key). There is a lot of useful example on Internet.
And i would want to create an object doing something like
$"car", "plane"$
like yo do ["car", "plane"] by default
If you don't want change the Python interpreter, you could have a less "native/hardcore" solution parsing the string and creating the objects that you want by yourself., something like:
>>> def my_parser(s):
... return [i.strip('"') for i in s.strip('$').split(', ')]
...
>>> my_parser('$"car", "plane"$')
['car', 'plane']
>>>
This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 8 years ago.
I'm writing a class in python that groups a bunch of similar variables together and then assembles them into a string. I'm hoping to avoid having to manually type out each variable in the generateString method, so I want to use something like:
for variable in dir(class):
if variable[:1] == '_':
recordString += variable
But currently it just returns a string that has all of the variable names. Is there a way to get at the value of the variable?
You can use the getattr() function to dynamically access attributes:
recordString += getattr(classobj, variable)
However, you probably do not want to use dir() here. dir() provides you with a list of attributes on the instance, class and base classes, while you appear to want to find only attributes found directly on the object.
You can use the vars() function instead, which returns a dictionary, letting you use items() to get both name and value:
for variable, value in vars(classobj).items():
if variable[:1] == '_':
recordString += value
I'm using Python and am trying to create a function that will look at the name of the object that is given as an argument and (among other things) create some globals that contain this name,
for example:
object1=someclass(args,kwds) #the object is an instance of a class that is given a certain name (e.g.object1)
def somefunc(some_argument):
global tau_some_argument
global ron_some_argument #e.t.c. for other variables (I also would like to assign some variables etc)
tau_some_argument=some_value1
ron_some_argument=some_value2
print ron_some_argument
print tau_some_argument
now what I want to happen if I call this function is as follows:
when I call
somefunc(object1)
I would like it to create some globals named tau_object1, ron_object1 and assign them values (the print statements are irrelevant), similarly if i called
somefunc(object2)
where object2 is another instance of a class I would like it to create globals: tau_object2, ron_object2, at the moment the function simply creates globals named tau_some_argument (as is obvious from the code).
Now I read somewhere that the names of python objects are immutable, unless they are a class or function so I don't know how to do this, from reading I get the feeling that I may need to use meta-classes but this feels like it's an overly complicated way of doing something that should be relatively easy.
Thanks in advance.
It sounds like a terrible idea...
def func(prefix):
g = globals()
g[prefix + '_tomato'] = 123
g[prefix + '_broccoli'] = 456
Whatever you are doing, it can probably be done with dictionaries, arrays, and other objects in a way that isn't fragile like the above method.
I'm not so sure about python but can't you just declare a global array and simply create the object indexed by the name of the object as a string?
tau_some_argument['object1'] = some_value1
ron_some_argument['object1'] = some_value2