__dict__

类的__dict__

首先看一下类的__dict__属性和类对象的__dict__属性

# -*- coding: utf-8 -*-


class A(object):
    """
    Class A.
    """

    a = 0
    b = 1

    def __init__(self):
        self.a = 2
        self.b = 3

    def test(self):
        print 'a normal func.'

    @staticmethod
    def static_test(self):
        print 'a static func.'

    @classmethod
    def class_test(self):
        print 'a calss func.'


obj = A()
print A.__dict__
print obj.__dict__

运行结果如下:

{'a': 0, '__module__': '__main__', 'b': 1, 'class_test': <classmethod object at 0x00000000021882E8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__init__': <function __init__ at 0x00000000023A5BA8>, 'test': <function test at 0x00000000023A5C18>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': '\n    Class A.\n    ', 'static_test': <staticmethod object at 0x00000000021881C8>}
{'a': 2, 'b': 3}

 由此可见, 类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里的

  对象的__dict__中存储了一些self.xxx的一些东西

 

.py的__dict__

例如,我们在mymodel.py中定义了一些类:

我们通过运行下面的语句:

import mymodel

print(mymodel.__dict__)

下面的部分结果(DeepResUNet和ONet和HybridResUNet均是mymodel.py定义的类):

'DeepResUNet': <class 'mymodel.DeepResUNet'>, 'HybridResUNet': <class 'mymodel.HybridResUNet'>, 'ONet': <class 'mymodel.ONet'>}

上述获得的类定义在经过实例化就可以生成类实例了。

print(mymodel.__dict__['DeepResUNet'](args))
 
posted @ 2021-02-21 17:26  为红颜  阅读(85)  评论(0编辑  收藏  举报