Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...