是否可以创建一个类,该类的每个实例将具有不同的类型?

这更多是一个理论问题,与实际问题无关。

考虑到您有一些课程:

class A():
    pass

a = A()
type(a)
# <class '__main__.A'>

有可能实现这样的事情吗?

from random import randint

class Randomized(type):
    def __new__(cls, name, bases, attrs):
        attrs['__qualname__'] += str(randint(0, 99))
        return super(Randomized, cls).__new__(cls, name, bases, attrs)

class A(metaclass=Randomized):
    pass

a = A()
b = A()
# as I was thinking:
type(a)
# <class '__main__.A75'>
type(b)
# <class '__main__.A23'>

Example above doesn't work as I expected because it seems that Randomized.__new__ called only once:

a = A()
b = A()
type(a)
# <class '__main__.A66'>
type(b)
# <class '__main__.A66'>

Related PEP about metaclasses: https://www.python.org/dev/peps/pep-3115/

评论
  • Doyle
    Doyle 回复

    You should place __new__ in A class to achieve desired behavior. Example:

    from random import randint
    
    
    class A:
        def __new__(cls, *args, **kwargs):
            random_cls = type('random_name' + str(randint(0, 99)), (object,), {})
            return random_cls()
    
    
    a = A()
    b = A()
    print(type(a))
    # <class '__main__.random_name90'>
    print(type(b))
    # <class '__main__.random_name22'>
    

    __new__ in metaclass is called on class A creation but not on creation of it's instances as you expected.