Python 类方法 - 有没有办法让调用更短?

发布于 2024-08-02 10:18:29 字数 699 浏览 4 评论 0原文

我正在使用Python,并且我在与调用它的包不同的包中创建了一个类。在这个类中,我添加了一个从我的主函数中调用的类方法。同样,它们位于单独的包中。调用类方法的行比我在其他地方看到的示例中想象的要长得多。这些示例倾向于从同一包中调用类方法 - 从而缩短调用语法。

这是一个我希望有所帮助的示例:

在“config”包中:

class TestClass :
   memberdict = { }

   @classmethod
   def add_key( clazz, key, value ) :
      memberdict[ key ] = value

现在在名为“test”的不同包中:

import sys
import config.TestClass

def main() :
   config.TestClass.TestClass.add_key( "mykey", "newvalue" )
   return 0

if __name__ == "__main__" :
    sys.exit( main() )

您可以看到“config.TestClass.TestClass.add_key”比正常的类方法调用要详细得多。有没有办法让它变得更短?也许是“TestClass.add_key”?我是否以一种奇怪的方式定义了某些东西(与 python 文件名匹配的类的情况?)

I am playing around with Python, and I've created a class in a different package from the one calling it. In this class, I've added a class method which is being called from my main function. Again, they are in separate packages. The line to call the class method is much longer than I thought it would be from the examples I've seen in other places. These examples tend to call class methods from within the same package - thus shortening the calling syntax.

Here's an example that I hope helps:

In a 'config' package:

class TestClass :
   memberdict = { }

   @classmethod
   def add_key( clazz, key, value ) :
      memberdict[ key ] = value

Now in a different package named 'test':

import sys
import config.TestClass

def main() :
   config.TestClass.TestClass.add_key( "mykey", "newvalue" )
   return 0

if __name__ == "__main__" :
    sys.exit( main() )

You can see how 'config.TestClass.TestClass.add_key' is much more verbose than normal class method calls. Is there a way to make it shorter? Maybe 'TestClass.add_key'? Am I defining something in a strange way (Case of the class matching the python file name?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深白境迁sunset 2024-08-09 10:18:29
from config.TestClass import TestClass
TestClass.add_key( "mykey", "newvalue" )
from config.TestClass import TestClass
TestClass.add_key( "mykey", "newvalue" )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文