在python模块中执行方法顺序 [英] Enforcing method order in a python module

查看:112
本文介绍了在python模块中执行方法顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理必须按特定顺序调用方法的模块的最Python方式是什么?

What is the most pythonic way to deal with a module in which methods must be called in a certain order?

作为一个例子,我有一个XML配置,在执行任何其他操作之前必须先阅读它,因为该配置会影响行为.必须首先使用提供的配置文件来调用parse_config().在调用parse_config()之前,无法调用其他支持方法,例如query_data().

As an example, I have an XML configuration that must be read before doing anything else because the configuration affects behavior. The parse_config() must be called first with the config file provided. Calling other supporting methods like query_data() won't work until parse_config() has been called.

我首先将其实现为单例,以确保在初始化时传递配置文件名,但是注意到模块实际上是单例,不再是类,而只是常规模块.

I first implemented this as a singleton to ensure that a filename for the config is passed at time of initialization, but noticing that modules are actually singletons, it's no longer a class, but just a regular module.

强制在模块中首先调用parse_config的最佳方法是什么?

What's the best way to enforce the parse_config being called first in a module?

编辑:值得注意的是该功能实际上是parse_config(configfile)

Worth noting is that the function is actually parse_config(configfile)

推荐答案

如果对象在调用之前无效,则在__init__中调用该方法(或使用工厂函数).您肯定不需要任何愚蠢的单例.

If the object isn't valid before it's called, then call that method in __init__ (or use a factory function). You don't need any silly singletons, that's for sure.

这篇关于在python模块中执行方法顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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