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