Is there a way to turn previously declared class variables into a list?

class variable python
python update class attributes
change class variable python
python class attributes
python class variable scope
pass variables between classes python
python class variables vs instance variables
python access class variable from method

If we have a class with variables, is there a way to turn those variables into a list?

For example:

class Son(_Dad):
    var1 = 'foo'
    var2 = 'bar'
    # code here to generate varList = ['foo', 'bar']

this class will be changed over time, and variables might be added and removed. Would it be possible to generate a list using the previously declared variables? I tried messing around with the dir() function but to the best of my knowledge, I could only get attributes from the class, and I need variables.

You can use vars() to do it (tested in Python 3.8.0). It will examine everything defined in the class up to the point it is used.

class _Dad: pass


class Son(_Dad):
    var1 = 'foo'
    var2 = 'bar'

    # Generate varlist = ['foo', 'bar']
    varlist = [value for key, value in vars().items() if not key.startswith('_')]
    print('varlist:', varlist)

    def method():  # Won't be included in varlist.
        pass

    var3 = 'baz'  # Won't be included in varlist.

Output:

varlist: ['foo', 'bar']

Python Class Attributes: Examples of Variables, This essentially overrides the class variable and turns it into an instance variable Let's go back to the Service I defined earlier and see how my use of a class all instances of Service are accessing and modifying the same list in Service. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Instance variables − Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created.

You can use:

[attr for attr in dir(class_instance) if not callable(getattr(class_instance, attr)) and not attr.startswith("__")]

where class_instance is an instance of your class.

Object Oriented Programming in Pyth: Class and Instance Variables , How To Code in Python 3 Understanding List Comprehensions in Python 3 Understanding Class and Instance Variables in Python 3 At the class level, variables are referred to as class variables, whereas reuse code and write code that is more readable, which in turn makes it more maintainable. Is there a way to list all Variables (Fields) of a class in C#. If yes than could someone give me some examples how to save them in a List and get them maybe using Anonymous Types (var).

You can do this in the class itself without creating it's object. Here I am leveraging locals and vars method. Check below:

class Abc:
    a = 5
    b = 3
    attr_list = locals().copy()
    all_vars = vars().copy()
    c = [all_vars[attr] for attr in attr_list if attr in all_vars and not callable(all_vars[attr]) and not attr.startswith("__")]

    def check_c(self):
        print self.c

k = Abc()
k.check_c() #prints [5,3]

just define all the variables before attr_list and then the variable c will contain the list of values of all the variables. Hope this helps.

An Introduction to Python Lists, And Python never creates a new list if you assign a list to a variable. For information on how to add items to a list once you've created it, see Modifying Lists below. If the transform is complex, or the list is large, this can be a lot faster than� To advance on this: variables should have the smallest possible scope that gets the job done. That's why index variables are declared in the for loop. It is also related to the rule of thumb: initialize things as late as possible. By implication then, since you want to have variables initialized, they should be declared as late as possible.

Have you thought about using a metaclass? You could grab all new class fields on its creation, and then use them to create either the list or the dictionary if needed.

>>>class DadMeta(type):
...    def __new__(mcs, name, bases, dct):
...        values_dict = {}
...        values_list = []
...        for name, value in dct.items():
...            if not callable(value) and not name.startswith("__"):
...                values_dict[name] = value
...                values_list.append(value)
...        
...        cls = super().__new__(mcs, name, bases, dct)   
...        cls.values_list = getattr(cls, "values_list", []) + values_list
...        cls.values_dict = {**getattr(cls, "values_dict", {}), **values_dict}
...               
...        return cls
...                
>>>class Dad(metaclass=DadMeta):
...    var_1 = "foo"
...    var_2 = "bar"
...
>>>Dad.values_list
['foo', 'bar']
>>>Dad.values_dict
{'var_1': 'foo', 'var_2': 'bar'}
>>>class Son(Dad):
...    var_3 = "test"
...    var_4 = "meh"
...
>>>Son.values_list
['foo', 'bar', 'test', 'meh']
>>>Dad.values_list
['foo', 'bar']
>>>Son.values_dict
{'var_1': 'foo', 'var_2': 'bar', 'var_3': 'test', 'var_4': 'meh'}

This should also work nicely with inheritance, if needed.

Variables and scope — Object-Oriented Programming in Python 1 , To define a new variable in Python, we simply assign a value to a label. For example, this is how we create a variable called count , which contains an integer Variables which are defined in the class body (but outside any class method) are Because we haven't declared a to be global, the assignment in the second line� This declaration is probably the most popular, as there was no alternative until ECMAScript 6. Variables declared with var are available in the scope of the enclosing function. If there is no

You might be looking for This answer here. In your case this would be:

a for a in dir(Son) if not a.startswith('__')]

Classes - Object-Oriented Programming in Python, Classes are a way of grouping together related data and functions which act upon In earlier versions of Python a distinction was made between built-in types We would list any parent classes in between round brackets before the colon, but If our attribute name is stored as a string value in a variable, we have to use� Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc.

Storing Multiple Values in Lists – Programming with Python, Questions. How can I store many values together? Objectives If we loop over a list, the loop variable is assigned to its elements one at a time: Using the previously declared list x , these would be the results of the index operations shown in the image: Use a for-loop to convert the string “hello” into a list of letters: ['h', 'e'� These are going to turn into variables in your code, which you will learn about momentarily. You also need a way to make images, whether reading in an existing image or creating a blank image. You need a way to operate on this images and their pixels looking at particular pixels see what color they are and setting the pixels in an image, you'll

15. Classes and Objects — the Basics — How to Think Like a , In object-oriented programming the focus is on the creation of objects which contain both data and A natural way to represent a point in Python is with two numeric values. The variable p refers to a Point object, which contains two attributes. If we call print_point(p) with point p as defined previously, the output is (3, 4). There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.. Local Variable. A local variable in Java can be declared locally in methods, code blocks, and constructors.

Programming FAQ — Python 3.8.5 documentation, What are the rules for local and global variables in Python? How do I convert a string to a number? How do I get a list of all instances of a given class? It can be a surprise to get the UnboundLocalError in previously working code In the example above you can access the outer scope variable by declaring it global:. There are some obscure exceptions, but in general, if a field is final, then every thread that uses your class will see the same value for the variable. Conversely, if a field is not final and multiple threads are using your class, you will need to worry about explicit synchronization using synchronized blocks and/or classes from java.util

Comments
  • You might be able to leverage the vars() method, which shows a number of the object's attributes: docs.python.org/3/library/functions.html#vars
  • i dont think python gives you a way to find all variables in a method and put them in a list. You can create a list and add all variables you are using by .append method
  • @Jawad. This is not happening in a method
  • I mean you can always do my_list = [var1, var2]
  • @Hierarchy009. Why do you need a list then? This seems a bit XY-ish. Why not use a dictionary (which you can subset from the class __dict__)?
  • This will return the methods too.
  • @EmmanuelBan Yes that's right. The linked answer (and of course your answer) handle this case too.
  • If the variable name is __foo it will be mangled as _Son__var1 and it won't print properly the variable name in that case.
  • It's python standard, that internal variables start and end with __ so in my example there is the need for a check at the end for __ aswell. Anyway, it's kind of personal preference if you want to treat variables only starting with __ as internal variables or not.
  • Can you please explain how it is going to solve the original question?