如何以编程方式将基于“自定义类"的单例对象转换为python模块? [英] How to convert a "custom class"-based singleton object programmatically into a python module?

查看:117
本文介绍了如何以编程方式将基于“自定义类"的单例对象转换为python模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式将单例对象转换为Python模块,这样我就可以通过通过模块导入单例对象的方法来直接使用此单例对象的方法,而不必将其作为对象属性进行访问. 以编程方式"是指我不想将类方法显式复制粘贴到模块文件中.我需要一种解决方法,使我可以将对象方法导入到另一个模块的全局范围中.

I would like to convert a singleton-object programmatically into a Python module so that I can use the methods of this singleton-object directly by importing them via the module instead of accessing them as object attributes. By "programmatically" I mean that I do not want to have to copy-paste the class methods explicitly into a module file. I need some sort of a workaround that allows me to import the object methods into to global scope of another module.

如果有人可以帮助我,我将非常感激.

I would really appreciate if someone could help me on this one.

这是一个基本的例子,应该可以说明我的问题:

Here is a basic example that should illustrate my problem:

class MyClass:
"""This is my custom class"""
    def my_method(self):
        return "myValue"

singleton = MyClass()

main_as_is.py

from mymodule import MyClass

myobject = MyClass()
print(myobject.my_method())

main_to_be.py

from mymodule import my_method # or from mymodule.singleton import my_method

print(my_method())

推荐答案

您可以使用与标准 random 模块使用.该模块中的所有功能实际上是Random类的私有"实例的方法.这对于模块的大多数常用用法很方便,尽管有时创建自己的Random实例很有用,这样您可以拥有多个独立的随机流.

You can use the same strategy that the standard random module uses. All the functions in that module are actually methods of a "private" instance of the Random class. That's convenient for most common uses of the module, although sometimes it's useful to create your own instances of Random so that you can have multiple independent random streams.

我修改了您的代码以说明该技术.我用单个下划线命名该类及其实例,因为它是 Python中通常使用的惯例来表示私有名称,但是请记住,这只是一个惯例,Python并没有采取任何措施来加强这种隐私.

I've adapted your code to illustrate that technique. I named the class and its instance with a single leading underscore, since that's the usual convention in Python to signify a private name, but bear in mind it's simply a convention, Python doesn't do anything to enforce this privacy.

class _MyClass:
    """ This is my custom class """
    def my_method(self):
        return "myValue"

_myclass = _MyClass()
my_method = _myclass.my_method

main_to_be.py

from mymodule import my_method

print(my_method())       

输出

myValue

顺便说一句,如果仅导入少量名称,或者从名称中清楚地知道它来自哪个模块(例如数学模块函数和常量),并且没有从多个模块导入,则from mymodule import method1, method2语法是可以的.否则,最好使用这种语法

BTW, the from mymodule import method1, method2 syntax is ok if you only import a small number of names, or it's clear from the name which module it's from (like math module functions and constants), and you don't import from many modules. Otherwise it's better to use this sort of syntax

import mymodule as mm
# Call a method from the module
mm.method1()

这样,很明显哪些名称是本地名称,哪些名称是导入的,以及它们从何处导入的.当然,它的类型更多,但是使代码整体更具可读性.并且消除了名称冲突的可能性.

That way it's obvious which names are local, and which ones are imported and where they're imported from. Sure, it's a little more typing, but it makes the code a whole lot more readable. And it eliminates the possibility of name collisions.

FWIW,这是一种自动添加所有_myclass方法而不显式列出它们的方法(但请记住,显式优于隐式").在"mymodule.py"的末尾,代替my_method = _myclass.my_method,添加以下内容:

FWIW, here's a way to automate adding all of the _myclass methods without explicitly listing them (but remember "explicit is better than implicit"). At the end of "mymodule.py", in place of my_method = _myclass.my_method, add this:

globals().update({k: getattr(_myclass, k) for k in _MyClass.__dict__ 
    if not k.startswith('__')})

我不建议这样做,因为它会将项目直接注入globals()字典中.请注意,该代码将添加所有类属性,而不仅仅是方法.

I'm not comfortable with recommending this, since it directly injects items into the globals() dict. Note that that code will add all class attributes, not just methods.

在您的问题中,您谈论的是单例对象.我们通常在Python中不使用单例,并且许多使用OOP语言的程序员都将它们视为反模式.参见 https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern 有关详细信息.对于此应用程序,完全完全不需要使用单例.如果您只想要_MyClass的一个实例,那么根本就不要创建它的另一个实例,只需使用mymodule为您创建的实例即可.但是,如果老板坚持要求您必须使用单身人士,请在此处中查看示例代码.

In your question you talk about singleton objects. We don't normally use singletons in Python, and many programmers in various OOP languages consider them to be an anti-pattern. See https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern for details. For this application there is absolutely no need at all to use a singleton. If you only want a single instance of _MyClass then simply don't create another instance of it, just use the instance that mymodule creates for you. But if your boss insists that you must use a singleton, please see the example code here.

这篇关于如何以编程方式将基于“自定义类"的单例对象转换为python模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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