#__dict__ in python
class LonelyBear(object):
class_attr01 = "default user defined class attr"
def user_defined_func_or_mtd(self):
pass
#<type 'dictproxy'>
print type(LonelyBear.__dict__)
#when visit class attr, you can use either class_name.__dict__[attr_name] or class_name.attr_name
if id(LonelyBear.__dict__["class_attr01"]) == id(LonelyBear.class_attr01):
print "when visit class attr, you can use either class_name.__dict__[attr_name] or class_name.attr_name"
#class_name.__dict__[func_or_mtd_name] is <function user_defined_func_or_mtd at 0x026F4670>
#class_name.func_or_mtd_name is <unbound method LonelyBear.user_defined_func_or_mtd>
func_managed_by_dictproxy = LonelyBear.__dict__["user_defined_func_or_mtd"]
method_managed_by_cls_ns = LonelyBear.user_defined_func_or_mtd
if func_managed_by_dictproxy != method_managed_by_cls_ns:
print "class_name.__dict__[func_or_mtd_name] is", func_managed_by_dictproxy
print "class_name.func_or_mtd_name is", method_managed_by_cls_ns
lb = LonelyBear()
an_inst_without_instance_attr = lb.__dict__
#<type 'dict'> {}
print type(an_inst_without_instance_attr), an_inst_without_instance_attr
print """an attr is searched first from instance(inst_name.user_defined_inst_attr, if avaible), then class(cls_name.user_defined_cls_attr),
then the internal(you can use dir(inst_name) to view any possible attr)[note: I am not considering __getattr__ and other hooks]"""
#AttributeError: 'str' object has no attribute '__dict__'
print "some internal type has no __dict__ attr".__dict__
No comments:
Post a Comment