当用作参数时,Python将导入的模块类评估为“类型”

时间:2018-03-19 11:36:21

标签: python

我明确地从外部模块导入了类。我可以创建这种类型的对象,但是当用作参数,即将类类型传递给方法时,该方法将类评估为“类型”。

使用命名空间前缀也是不可解析的。该方法很好地评估python基类型,即传递int被计算为int ...

test.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)

factory.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

example_factory_type.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')

i_factory_type.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

2 个答案:

答案 0 :(得分:2)

这个说法是错误的:

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

答案 1 :(得分:0)

一个类不是其超类的实例; isinstance(ExampleFactoryType, IFactoryType)永远是假的。这适用于ExampleFactoryType的实例(例如obj),但不适用于类本身。