2016-10-27 68 views
-1

我需要定义扩展 Python的标准数学模块类,而不将其实例化一个类(没有必要的,在类的所有方法都是静态的):继承数学方法与只有静态方法

import math 

class more_math(math): 

    @staticmethod 
    def add_func(x): 
     return math.sqrt(x)+1 

上面的代码运行不正常(脚本退出),与错误:

TypeError: Error when calling the metaclass bases 
    module.__init__() takes at most 2 arguments (3 given) 

当类声明的上方设置为class more_math:more_math.add_func(x)被称为没有错误。但是,more_math.sqrt(x) [sqrt是方法math]不能被调用,因为more_math不具有math作为其基类。

想法如何可以正确设置?

+4

Python的'math'是不是一类。 – jwodder

+4

有*没有*“标准数学课”。这不是Java;你导入模块,而不是类。 – user2357112

回答

2

认真考虑你是否真的需要提供函数的数学工具。你几乎肯定不会;你可能只需要提供你的演员。也就是说,如果你确实需要提供一个实现所有标准数学函数的more_math模块,最简单的方法就是做一个from math import *。这会将math模块定义的每个功能都带入您的模块。这被认为是很糟糕的做法,因为它会污染你的模块的命名空间,并且很难判断实际使用的是什么。但是,在这种情况下,模块命名空间的污染正是你想要的

+0

虽然上面的答案是很好的指导,但我可能没有正确地传达这个问题:我想more_math来保存数学+附加函数的所有功能。我真的不想改变数学[基本上_ever_,这是@gbe上面说的]。 –

+2

@GG_Python:我想你已经误解了这个答案的建议是从数学导入*开始。如果你在'more_math'模块中这样做,那么除了你定义的其他任何东西外,该模块还会公开'math'中的所有函数和常量。这似乎正是你要求的。 – Blckknght

0

由于@ user2357112评论数学是一个模块,而不是一个类。你可以简单地通过创建more_math.py文件中创建一个more_math模块:

from math import * 

def add_func(x): 
    return sqrt(x)+1 

该模块可与import more_mathfrom more_math import add_func进口。

0

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