Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the class type of a class after inserted data

I want to create a class in python, which should work like this:

  1. Data assigned, maybe bound to a variable (eg a = exampleclass(data) or just exampleclass(data))

  2. Upon being inserted data, it should automatically determine some properties of the data, and if some certain properties are fullfilled, it will automatically...

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

like image 419
user1187139 Avatar asked Feb 04 '12 19:02

user1187139


1 Answers

Why not using a factory method? This one will decide which class to instanciate depending on the passed data. Using your example:

def create_number(number):
    if number < 1000:
        return SmallNumber(number)
    return BigNumber(number)
like image 130
juliomalegria Avatar answered Oct 28 '22 06:10

juliomalegria