如何静态调用另一个静态方法(在类体中)?

时间:2017-09-07 01:55:45

标签: python python-3.x dictionary static static-methods

我如何静态(即类正文中的 )调用staticmethod调用Python 3.6中的另一个staticmethod? 我想用staticmethod初始化我班级的静态成员。问题是我在创建之前尝试引用我的类(与this question不同)。

以下是我的问题的一个例子。我实际上是尝试使用字典理解来初始化静态字典,它使用静态函数,所以我也包含了一个例子。我设法使用基本循环解决了这个问题,但也有other ways静态地使用了解。

class Test:

    @staticmethod
    def something(q):
        return q + 10

    @staticmethod
    def foo(x):
        return "Hello {0}".format(Test.something(x))

    # **** foo is called, but throws error at call to Test.something() ****
    #print(foo.__func__(4))    

    # something() is also used by itself.
    print(something.__func__(2))



    # My problem involved initializing a dictionary. Solved using loop.
    a = [1,2,3,4]

    #d = {k: "yup" for k in a}          # Dictionary comprehension works
    #d = {k: Test.something.__func__(k) for k in a}     # Error, Test/something not defined

    d = {}
    for k in a:
        d[k] = something.__func__(k)   




print(Test.foo(5))  # Works, class defined (but not what I need).

0 个答案:

没有答案