Python:可以从类内调用静态方法,但不限定名称 [英] Python: possible to call static method from within class without qualifying the name

查看:705
本文介绍了Python:可以从类内调用静态方法,但不限定名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很讨厌:

class MyClass:
    @staticmethod
    def foo():
        print "hi"

    @staticmethod
    def bar():
        MyClass.foo()

有没有办法使这个工作没有在调用中命名MyClass?即,我可以在最后一行上说 foo()

Is there a way to make this work without naming MyClass in the call? i.e. so I can just say foo() on the last line?

推荐答案

p>没有办法使用 foo 并得到你想要的。没有隐式类范围,因此 foo 是本地或全局的,你不想要。

There is no way to use foo and get what you want. There is no implicit class scope, so foo is either a local or a global, neither of which you want.

您可能会发现类方法更有用:

You might find classmethods more useful:

class MyClass:
    @classmethod
    def foo(cls):
        print "hi"

    @classmethod
    def bar(cls):
        cls.foo()

这样,至少你不必重复类的名称。

This way, at least you don't have to repeat the name of the class.

这篇关于Python:可以从类内调用静态方法,但不限定名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆