Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of assigning a class to a variable in Python

Tags:

python

Is there any good reason why one would assign a class to a variable as shown in the code below ? What are some useful/interesting things one can do thanks to that mechanic ?

class foo:

    # Some initialization stuff
    def __init__(self):
        self.x = 0

    # Some methods and other stuff

myVar = foo
like image 845
Leop Avatar asked Feb 27 '19 16:02

Leop


People also ask

What is the use of class variable in Python?

Class variables are defined within the class construction. Because they are owned by the class itself, class variables are shared by all instances of the class. They therefore will generally have the same value for every instance unless you are using the class variable to initialize a variable.

Can we assign a class to a variable in Python?

Use dot notation or setattr() function to set the value of a class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.

What is the use of class variable?

A class variable is an important part of object-oriented programming (OOP) that defines a specific attribute or property for a class and may be referred to as a member variable or static member variable.

What happens when we assign variable in Python?

The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value.


2 Answers

The case I've seen most often in production code is dependency injection or "compile-time" configuration.

For example, I may have some classes that implement some strategy or command, but I don't have the details for the constructor yet.

class StrategyOne:...
class StrategyTwo:...

def my_func(vars, Strategy):
    x = some_calculation(vars)
    st = Strategy(x)

An example of using this as configuration can be seen in the django-rest-framework docs

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('id', 'account_name', 'users', 'created')

I think most uses cases fall into the principle of "I don't want to couple to this particular class". Another level of indirection and all.

Take the type checking example for instance. The loop over the collection of types [x for x in lst if isinstance(x, types)] does not depend on any particular types and is thus decoupled from the contents of the list of types.

like image 85
munk Avatar answered Oct 02 '22 23:10

munk


One important use-case certainly is for type checking or filtering:

class Foo:
    pass

lst = ["bla", 42, Foo()]
types = (str, Foo)
filtered = [x for x in lst if isinstance(x, types)]
# ['bla', <__main__.Foo at 0x7fa3422aa668>]

Another might be for dynamically creating instances of some class, e.g. with defaultdict.

class Bar:
    def __init__(self):
        self.value = 0

from collections import defaultdict
d = defaultdict(Bar)
for x, y in [(1,1), (1,2), (2,3), (2,4)]:
    d[x].value += y
print(d[1].value) # 3
like image 22
tobias_k Avatar answered Oct 03 '22 00:10

tobias_k