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
Related
This question already has answers here:
Convert string to Python class object?
(10 answers)
Closed 4 years ago.
I checked I have a string whose content is a function name, how to refer to the corresponding function in Python? but it is not the question I want to ask.
The question is: I have a string 'ABC' and I want to create an instance of class ABC as:
my_obj = ABC ()
The input 'ABC' is read from Python arguments (argparse).
The class is already defined and imported.
You can use a dictionary:
d = {'ABC': ABC} # where ABC is the class object
my_obj = d['ABC']()
This should be preferable to solutions using global (poor practice) and eval (security risks).
This may seem cumbersome until you realise that classes and class instances are first class objects in Python. You should never rely on evaluating strings to call a Python object. Be explicit, even if it's not elegant.
This question already has answers here:
Python: access class property from string [duplicate]
(4 answers)
Closed 4 years ago.
I am using Python 3.5 and wish to do something like this
I have created a class which has variables Bitcoin, Monero , 'Etherum' ,etc with various integer values ,I wish to extract them
var1="Bitcoin"
value=classobj.var1 // there is a class which has a variable called Bitcoin and its value is 10 I wish to get its value using classobject.Bitcoin but the variable called var is Dynamic
print (value)
How do I achieve the same ?
EDIT
I know it is possible using switch statement but I am looking for other ways
This is almost always a bad idea—and you really should explain why your design looks like this, because it's probably a bad design.
But "almost always" isn't "always", so Python has a way to do this:
getattr(classobj, var)
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
This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 7 years ago.
I'd like to be able to access the name of a variable that is passed to a function as e.g.
def f(x):
'''Returns name of list/dict variable passed to f'''
return magic(x)
>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None
I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)
Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.
Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.
This question already has answers here:
Does it make a difference using self for a temporary variable in a Python method?
(4 answers)
Closed 7 years ago.
Sorry, this is a really basic question, but I am just wondering when it is necessary to prepend self._ to variable declarations within methods? Every time I declare a variable within a method should I declare it with self._ included? Is there any situation where I should not do this?
Which of these methods would be valid for example (for some hypothetical class):
def thing_counter(self, thing):
length_of_thing = len(thing)
return length_of_thing
OR
def thing_counter(self, thing):
self._length_of_thing = len(thing)
return self._length_of_thing
Both work, but which would be strictly correct?
I know that a variable declaration is not really needed here, I am just trying to use a simple example.
Cheers!
Both work equally.
In the first version, length_of_thing will be created inside the function, and the return will return a copy to the caller. length_of_thing itself will not exist anymore after the return.
In the second one, self._length_of_thing will be created, not inside the function, but inside the instance of the class. The result is that it will be visible to all other methods. And the return still returns a copy.
So possibly this version uses a little more memory, as the variable self._length_of_thing remains alive till the instance of the class is destroyed.