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
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.
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.
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.
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.
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.
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
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