使用type新建一个类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TH_NUM/article/details/81870108
class A(object):
    def __init__(self,a):
        self.a=a
    def print(self):
        print("this is function A")

class Acopy(A):

    def  __init__(self,a,b):
        print("Acopy:",self.__class__)

        super(Acopy,self).__init__(a)
        self.a=a
        self.b=b


    def printAcopy(self):
        print("this is function A")
        print("Acopy dict:", self.__dict__)

class  Bcopy(A):
    def __init__(self,a,b,c):
        print("Bcopy:",self.__class__)
        # 如果这里是 super(Bcopy,self).__init__(a)会报错
        super(self.__class__,self).__init__(a,b)
        self.b=b
        self.c=c
    def printBcopy(self):
        print("this is B copy!")


ta=Acopy(1,1)
#print(Bcopy.__dict__)
cls=type(ta.__class__.__name__,(ta.__class__,),dict(Bcopy.__dict__))
t1=cls(2,2,2)
print(Acopy.__dict__)

输出:

Acopy: <class '__main__.Acopy'>
Bcopy: <class '__main__.Acopy'>
Acopy: <class '__main__.Acopy'>
{'__module__': '__main__', '__init__': <function Acopy.__init__ at 0x00000000025A56A8>, 'printAcopy': <function Acopy.printAcopy at 0x00000000025A5730>, '__doc__': None}

猜你喜欢

转载自blog.csdn.net/TH_NUM/article/details/81870108