我已经从外部模块显式导入了类。我可以创建这种类型的对象,但当用作参数时,即将类类型传递给方法时,该方法将类计算为“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
类不是它的超类的实例
isinstance(ExampleFactoryType, IFactoryType)
将始终为false。这适用于ExampleFactoryType的实例(例如obj
),但不适用于类本身这种说法是错误的:
你应该说:
ExampleFactoryType
的实例将是IFactoryType
的实例,但类本身不是其基类的实例所有python类都是
type
的实例。甚至类型type
本身也是一个实例也许这有助于您理解类型和实例之间的区别:
相关问题 更多 >
编程相关推荐