2016-10-27 67 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