python – 获取类的self .__ module__,无论如何导入

栏目: Python · 发布时间: 7年前

内容简介:我有一个库类,它取决于它是如何导入的,一个依赖于self .__ module__的方法来识别更改行为 – 取决于我是相对还是绝对地导入它.有没有办法强制类的self .__ name__属性绝对回归?我意识到一个解决方案是强制每个人以相同的方式导入子类,但是想知道是否有办法从库的角度强制它.总结结构

我有一个库类,它取决于它是如何导入的,一个依赖于self .__ module__的方法来识别更改行为 – 取决于我是相对还是绝对地导入它.有没有办法强制类的self .__ name__属性绝对回归?

我意识到一个解决方案是强制每个人以相同的方式导入子类,但是想知道是否有办法从库的角度强制它.

总结结构

我在库中有一个模块

project/
    mylib/
        foo.py
            LibraryClass
            def get_name(self):
                return "%s.%s.%s" % \
                    (self.__module__, self.__class__.__name__, self.some_init_property)
    prog/
        utils.py
            fooClass(LibraryClass)
        bar.py
            def some_func()
               #see below

在mylib中,我有一个导入器通过我们的django项目的设置文件中的classname字符串导入LibraryClass的所有子类.

基本上,我们看到的行为取决于您的导入方式.

所以我在bar.py中观察到两种行为:

def some_func_absolute():
    from prog.utils import fooClass
    f = fooClass("lalala")
    print f.get_name()
    #prints prog.utils.fooClass.lalala

与

def some_func_relative():
    from utils import fooClass
    f = fooClass("lalala")
    print f.get_name()
    #prints foo.fooClass.lalala

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Hackers

Hackers

Steven Levy / O'Reilly Media / 2010-5-30 / USD 21.99

This 25th anniversary edition of Steven Levy's classic book traces the exploits of the computer revolution's original hackers -- those brilliant and eccentric nerds from the late 1950s through the ear......一起来看看 《Hackers》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具