How to convert a string to a class name? [duplicate] - python

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.

Related

Can an instance's variable name be defined using concatenation? [duplicate]

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

How to call and print an item from another python file [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 4 years ago.
In Java, I can override the toString() method of my class. Then Java's print function prints the string representation of the object defined by its toString(). Is there a Python equivalent to Java's toString()?
For example, I have a PlayCard class. I have an instance c of PlayCard. Now:
>>> print(c)
<__main__.Card object at 0x01FD5D30>
But what I want is something like:
>>> print(c)
A♣
How do I customize the string representation of my class instances?
I'm using Python 3.x
The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__ to aid in debugging.
See here for more information:
Special Method Names - Basic Customization
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples
How to make a class JSON serializable
Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

python introspection - get name of variable passed to function [duplicate]

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.

Get the value of variables in dir(class) [duplicate]

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

How do I change the string representation of a Python class? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 4 years ago.
In Java, I can override the toString() method of my class. Then Java's print function prints the string representation of the object defined by its toString(). Is there a Python equivalent to Java's toString()?
For example, I have a PlayCard class. I have an instance c of PlayCard. Now:
>>> print(c)
<__main__.Card object at 0x01FD5D30>
But what I want is something like:
>>> print(c)
A♣
How do I customize the string representation of my class instances?
I'm using Python 3.x
The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__ to aid in debugging.
See here for more information:
Special Method Names - Basic Customization
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples
How to make a class JSON serializable
Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Categories

Resources