Python 类方法 - 有没有办法让调用更短?
我正在使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)