Python导入模块类作为“type”进行评估时,当用作参数时

2024-09-30 06:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经从外部模块显式导入了类。我可以创建这种类型的对象,但当用作参数时,即将类类型传递给方法时,该方法将类计算为“type”

使用名称空间前缀也是不可解析的。该方法可以很好地计算python基类型,即传递int的值是int

测试.py

import os
import sys
import math
import time
import traceback
import datetime
import argparse

from i_factory_type import IFactoryType
from example_factory_type import ExampleFactoryType
from factory import Factory

if __name__ == "__main__":

    obj = ExampleFactoryType()
    print(type(obj))
    print(isinstance(obj, IFactoryType))
    obj.make()
    factory = Factory()
    factory.register('123', ExampleFactoryType)

工厂.py

'''
Polymorphic factory that creates IFactoryTypes with dispatching
'''

from i_factory_type import IFactoryType

'''
Implementation of factory
'''
class Factory:

    def Factory(self):

        self.registry = dict()

    def register(self, i_id, i_type):

        print(isinstance(i_type, IFactoryType))
        print(i_type.__class__)
        assert( isinstance(i_type, IFactoryType) )

        self.unregister_type(i_id)

        self.registry[i_id] = staticmethod(i_type)

    def unregister(self, i_id):

        if i_is in self.registry:
            del self.registry[i_id]

    def clear(self):

        self.registery.clear()

    def make_object(self, i_id, *i_args):

        ret = None

        if i_id in self.registry:
            ret = self.registry[i_id](i_args)

        return ret

示例\工厂\类型.py

'''
Base type for factory create method
'''

from i_factory_type import IFactoryType

'''
Interface for factory creation
'''
class ExampleFactoryType(IFactoryType):

    @staticmethod
    def make(*i_args):

        print('factory make override')

工厂类型.py

'''
Base type for factory create method
'''


'''
Interface for factory creation
'''
class IFactoryType:

    @staticmethod
    def make(*i_args):

        raise NotImplementedError('Must override factory type')

输出:

<class 'example_factory_type.ExampleFactoryType'>
True
factory make override
False
<class 'type'>
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    factory.register('123', ExampleFactoryType)
  File "F:\code\factory.py", line 20, in register
    assert( isinstance(i_type, IFactoryType) )
AssertionError

Tags: frompyimportselfid类型makefactory
2条回答

类不是它的超类的实例isinstance(ExampleFactoryType, IFactoryType)将始终为false。这适用于ExampleFactoryType的实例(例如obj),但不适用于类本身

这种说法是错误的:

assert( isinstance(i_type, IFactoryType) )

你应该说:

assert issubclass(i_type, IFactoryType)

ExampleFactoryType的实例将是IFactoryType的实例,但类本身不是其基类的实例

所有python类都是type的实例。甚至类型type本身也是一个实例

也许这有助于您理解类型和实例之间的区别:

obj = ExampleFactoryType()
isinstance(obj, ExampleFactoryType) # True
isinstance(obj, IFactoryType) # True
isinstance(ExampleFactoryType, IFactoryType) # False
issubclass(ExampleFactoryType, IFactoryType) # True
isinstance(ExampleFactoryType, type) # True
isinstance(IFactoryType, type) # True

相关问题 更多 >

    热门问题