python - 在python中构造类属性时访问类类型?

标签 python

我想这样做:

class MyThing(object):
    def __init__(self,owning_cls):
        self.owning_cls = owning_cls

class MyClass(object):
    thing = MyThing(self.__class__)

print MyClass.thing.owning_cls

这不起作用 - 因为在 MyClass 的类构造中没有 self 可供引用。

有什么方法可以实现这一点(如果我们将其作为实例属性,这显然是微不足道的,但我想成为一个类属性!)?

最佳答案

在类声明之后立即执行调用:

class MyClass(object): pass
MyClass.thing = MyThing(MyClass)

关于python - 在python中构造类属性时访问类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11229965/

相关文章:

python - 如何使用python将字符串更改为由 ','切割的列表?

python - Python : import in the middle of a file 中的好习惯或坏习惯

python - 在 python 的 tkinter 中,我怎样才能制作一个标签,这样你就可以用鼠标选择文本?

python - 在没有管理员权限的情况下安装 rpy2

python - 图像不响应不同的按键 Pygame Python

python - 使用 Python 根据特定列拆分 csv 文件

python - 监控单个文件

python - 在 setup.py 中清理 C++ 扩展构建目录

python - 如何检查我的代码中的 pep8 标准

python - LibreOffice 将 .docx 并行转换为 .pdf 效果不佳