math
不是类,它是类types.ModuleType
的实例。您可以使用isinstance(math, types.ModuleType)
进行验证,这将返回True
。通常你不能定义从另一个类的实例继承的子类。但是,它是可能与一些hackery。
(我从ActiveState的网站上,inheriting from an instances配方的想法。)
既然是一个黑客,一个可能不希望在生产代码中使用它。不过,我认为你(和其他读者)可能会觉得它是一个有趣的,如果没有用的话。
脚本more_math.py
:
from copy import deepcopy
import math
import sys
def class_from_instance(instance):
copy = deepcopy(instance.__dict__)
def __init__(self, *args, **kwargs):
super(InstanceFactory, self).__init__(*args, **kwargs)
self.__dict__.update(copy)
InstanceFactory = type('InstanceFactory',
(instance.__class__,),
{'__init__': __init__})
return InstanceFactory
class MoreMathModule(class_from_instance(math)):
@staticmethod
def added_func(x):
return math.sqrt(x)+1
# Replace this module with an instance of the class above.
ref, sys.modules[__name__] = sys.modules[__name__], MoreMathModule('more_math')
if __name__ == '__main__':
import more_math
x = 42
print('more_math.sqrt({}) -> {:.6f}'.format(x, more_math.sqrt(x)))
print('more_math.added_func({}) -> {:.6f}'.format(x, more_math.added_func(x)))
输出:
more_math.sqrt(42) -> 6.480741
more_math.added_func(42) -> 7.480741
Python的'math'是不是一类。 – jwodder
有*没有*“标准数学课”。这不是Java;你导入模块,而不是类。 – user2357112