简体   繁体   English

Python类方法 - 有没有办法缩短调用次数?

[英]Python class method - Is there a way to make the calls shorter?

I am playing around with Python, and I've created a class in a different package from the one calling it. 我正在玩Python,我在一个不同的包中创建了一个类来调用它。 In this class, I've added a class method which is being called from my main function. 在这个类中,我添加了一个从我的main函数调用的类方法。 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: 在'config'包中:

class TestClass :
   memberdict = { }

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

Now in a different package named 'test': 现在在一个名为'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. 您可以看到'config.TestClass.TestClass.add_key'如何比普通的类方法调用更冗长。 Is there a way to make it shorter? 有没有办法缩短它? Maybe 'TestClass.add_key'? 也许'TestClass.add_key'? Am I defining something in a strange way (Case of the class matching the python file name?) 我是否以一种奇怪的方式定义了一些东西(与python文件名匹配的类的情况?)

from config.TestClass import TestClass
TestClass.add_key( "mykey", "newvalue" )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM