The codes are like this:
class Test: a = 1 def __init__(self): self.b=2
When I make an instance of Test
, I can access its instance variable b
like this(using the string "b"):
test = Test() a_string = "b" print test.__dict__[a_string]
But it doesn't work for a
as self.__dict__
doesn't contain a key named a
. Then how can I accessa
if I only have a string a
?
Thanks!
Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.
To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.
String Indexing Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.
Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not.
To get the variable, you can do:
getattr(test, a_string)
use getattr this way to do what you want:
test = Test() a_string = "b" print getattr(test, a_string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With