Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access the class variable by string in Python?

Tags:

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!

like image 427
Hanfei Sun Avatar asked Nov 09 '12 06:11

Hanfei Sun


People also ask

How do you access class variables in Python?

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.

How do you access a class variable?

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.

How do you access data from a string in Python?

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.

How do I find the class of a string in Python?

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.


2 Answers

To get the variable, you can do:

getattr(test, a_string) 
like image 96
kindall Avatar answered Sep 28 '22 13:09

kindall


use getattr this way to do what you want:

test = Test() a_string = "b" print getattr(test, a_string) 
like image 28
Artsiom Rudzenka Avatar answered Sep 28 '22 12:09

Artsiom Rudzenka