python 中的__dict__

类的__dict__属性和类对象的__dict__属性

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


class TestDict(object):

    a = 0
    b = 1

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

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

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

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


if __name__ == '__main__':
    obj = TestDict()
    print('class __dict__:', TestDict.__dict__)
    print('class obj __dict__:', obj.__dict__)

输出结果

  • 类的__dict__:
('class __dict__:', dict_proxy({'a': 0, '__dict__': , '__module__': '__main__', 'b': 1, 'static_test': , 'test': , '__weakref__': , 'class_test': , '__init__': , '__doc__': None}))

dict里存放类的静态函数、类函数、普通函数、全局变量以及一些内置的属性

  • 类对象的__dict__
('class obj __dict__:', {'a': 2, 'b': 3})

类对象的__dict__存放类的属性:self.xxx

继承关系中的__dict__

# -*- coding: utf-8 -*-
class Parent(object):
    a = 0
    b = 1

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

    def parent_test(self):
        pass


class Child(Parent):
    a = 4
    b = 5

    def __init__(self):
        super(Child, self).__init__()
        self.b = 7
        self.c = 8

    def child_test(self):
        pass


if __name__ == '__main__':
    parent_obj = Parent()
    child_obj = Child()
    print('Parent __dict__:', Parent.__dict__)
    print('Child __dict__:', Child.__dict__)
    print('Parent obj __dict__:', parent_obj.__dict__)
    print('Child obj __dict__:', child_obj.__dict__)

输出

('Parent __dict__:', dict_proxy({'a': 0, '__module__': '__main__', 'b': 1, 'parent_test': , '__dict__': , '__weakref__': , '__doc__': None, '__init__': }))
('Child __dict__:', dict_proxy({'a': 4, '__module__': '__main__', 'b': 5, '__doc__': None, '__init__': , 'child_test': }))
('Parent obj __dict__:', {'a': 2, 'b': 3})
('Child obj __dict__:', {'a': 2, 'c': 8, 'b': 7})

可以看出

  • 继承关系,父类的__dict__并不会影响子类的__dict__因为
  • 子类__init__初始化了父类的__init__, 才会将父类对象的属性加到子类对象的__dict__
def __init__(self):
    super(Child, self).__init__()

应用

python中,用__dict__可以达到一些简化代码的目的

  • 简单例子:
class Person:  
    def __init__(self,_obj):
        self.name = _obj['name']  
        self.age = _obj['age']  
        self.energy = _obj['energy']  
        self.gender = _obj['gender']  
        self.email = _obj['email']  
        self.phone = _obj['phone']  
        self.country = _obj['country']  

是不是很繁琐?用dict一句话就可以搞定

class Person:  
    def __init__(self,_obj):  
        self.__dict__.update(_obj)
  • 复杂例子
    在适配器模式中,
class Synthesizer:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'the {} synthesizer'.format(self.name)

    def play(self):
        return 'is playing an electronic song'


class Human:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return '{} the human'.format(self.name)

    def speak(self):
        return 'says hello'

class Computer:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'the {} computer'.format(self.name)

    def execute(self):
        return 'executes a program'


class Adapter:

    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.__dict__.update(adapted_methods)
        print ("self.__dict__:", self.__dict__)

    def __str__(self):
        return str(self.obj)


def main():
    objects = [Computer('Asus')]
    synth = Synthesizer('moog')
    objects.append(Adapter(synth, dict(execute=synth.play)))
    human = Human('Bob')
    objects.append(Adapter(human, dict(execute=human.speak)))

    for i in objects:
        print('{} {}'.format(str(i), i.execute()))

类Adapterself.__dict__.update(adapted_methods),其实相当于

class Adapter:
    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.execute = adapted_methods

def main():
  objects.append(Adapter(synth, synth.play))

打印结果可以看出来

('self.__dict__:', {'execute': >, 'obj': <__main__.Synthesizer instance at 0x027B1CB0>})

你可能感兴趣的:(python 中的__dict__)