I want to create a class in python, which should work like this:
-
Data assigned, maybe bound to a variable (eg
a = exampleclass(data)or justexampleclass(data)) -
Upon being inserted data, it should automatically determine some properties of the data, and if some certain properties are fullfilled, it will automatically…
-
… change class to another class
The part 3 is the part that i have problem with. How do i really change the class inside of the class? for example:
If I have two classes, one is Small_Numbers, and the other is Big_numbers; now I want any small_number smaller than 1000 to be transferred into a Big_number and vice versa, testcode:
a = Small_number(50)
type(a) # should return Small_number.
b = Small_number(234234)
type(b) # should return Big_number.
c = Big_number(2)
type(c) # should return Small_number.
Is this possible to do?
Using a factory method is the usual way to solve this, especially since instantiating a class is indistinguishable from calling a function in Python.
However, if you really want, you can assign to
self.__class__:This works as expected:
If assigning to
self.__class__seems too strange, then you can override__new__instead. This method is called before__init__is called and it can be used to pick the class to instantiate: