I have a lengthy, repetitive code full of classes where they each do almost the same thing, and I was trying to do something like this to shorten it:
def newClass(cName, para):
string = '''class '''+cName+'''(str):
def __new__(cls, num):
return(str.__new__(cls, func('''+para+''')))'''
exec(string)
but the new class is neither a part of newClass
or defined on its own, how can I make it so it creates the new class as if it were not defined in a function? If that's impossible, how can I make it so that I can do something like:
newClass('Fun', 'p')
newClass.Fun('inp')
Edit: I am making a base conversion program, and wanted to be able to do things that python does not do like bin(a) + bin(b)
. Here is a simplified version of one of my classes:
class Bin(str):
'''Binary (base 2) number'''
def __new__(cls, num):
return(str.__new__(cls, baseconv(num, 2, '01')))
def __int__(self):
return(intconv(self, 2, '01'))
def __add__(a, b):
return(Bin(a.__int__() + b.__int__()))
def __sub__(a, b):
return(Bin(a.__int__() - b.__int__()))
...
class Ter(str):
'''Ternary (base 3) number'''
def __new__(cls, num):
return(str.__new__(cls, baseconv(num, 3, '012')))
def __int__(self):
return(intconv(self, 3, '012'))
def __add__(a, b):
return(Ter(a.__int__() + b.__int__()))
def __sub__(a, b):
return(Ter(a.__int__() - b.__int__()))
...
Where baseconv
and intconv
are two functions I've defined previously.