关于python的内置方法,希望能用一个简单的例子帮到你: =========test.py class a(object): name = "Jim" def __setattr__(self,name,value): self.__dict__[name] = value def __getattr__(self,name): return name b = a() print dir(b) print b.__dict__ print b.name print b.notexists print b.name = "change" print dir(b) print b.__dict__ print b.name print b.notexists ===========运行结果======== %python test.py ['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'name'] {} Jim notexists ['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'name'] {'name': 'change'} change notexists ============================ 可以看到刚开始的时候b的__dict__对象里面是空的没有东西,当我们使用b.name访问的时候直接访问到的之前定义好的name属性:"Jim" 当我们使用b.name = "change"后就默认调用了内置方法__setattr__,此时我并没有直接操作self.name属性,而是直接在修改了self.__dict__['name'] = 'change'.之后当我再用b.name访问的时候获得的就是__dict__中的name属性的值。 于是我们可以看到__getattr__方法首先是在__dict__中找属性名,然后在实例的属性中找 ,然后再调用__getattr__方法获得值。 希望能帮到你
dict: 类与对象的所有成员;
类输出的是全局的函数,变量等信息。
对象输出的只是对象拥有的普通变量而已
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
# -*- coding: utf8 -*-
#python 2.7
#xiaodeng
class JsonDict(dict):
def __getattr__(self,attr):
try:
return self[attr]
except KeyError:
raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
#可以重写dict,使之通过“.”调用
def __setattr__(self,attr,value):
self[attr] = value
j=JsonDict(name='python',age='28')
print j.name
print j.age
问题:
1、以上是高人写的一段代码,self[attr]和self[attr] = value表示什么意思?按照输出来看是dict,可以理解为这样写就固定是一个dict结构么?
2、__getattr__和__setattr__怎么理解,始终没太明白,网上查资料也没查出一个非常透彻的说明(我大概理解他是一个内置的办法,通常在类中会用到,有点似懂非懂)
3、PS:我是自学python,没其他语言基础,有些地方理解有点慢,盼大神指点 收起
#python 2.7
#xiaodeng
class JsonDict(dict):
def __getattr__(self,attr):
try:
return self[attr]
except KeyError:
raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
#可以重写dict,使之通过“.”调用
def __setattr__(self,attr,value):
self[attr] = value
j=JsonDict(name='python',age='28')
print j.name
print j.age
问题:
1、以上是高人写的一段代码,self[attr]和self[attr] = value表示什么意思?按照输出来看是dict,可以理解为这样写就固定是一个dict结构么?
2、__getattr__和__setattr__怎么理解,始终没太明白,网上查资料也没查出一个非常透彻的说明(我大概理解他是一个内置的办法,通常在类中会用到,有点似懂非懂)
3、PS:我是自学python,没其他语言基础,有些地方理解有点慢,盼大神指点 收起
j=JsonDict(name='python',age='28') print j.name print j.age print j['age'] --这几个调用方法都没有报错,好像能当dict去用,似懂非懂。我有更好的答案
推荐于2016-08-04 19:02:13
最佳答案
__getattr__为内置方法,当使用点号获取实例属性时,如果属性不存在就自动调用__getattr__方法 __setattr__当设置类实例属性时自动调用,如j.name=5 就会调用__setattr__方法 self.[name]=5 因为这个类是从dict继承来的,是dict的超类 所以 self[attr]=value 相当于调用dict的下标方法 与 a={} ; a[attr]=value意思一样