python object and class

来源:互联网 发布:风险矩阵图依据 编辑:程序博客网 时间:2024/05/21 13:59
pyhton 的class 与java,c++的大不相同,经过一段时间的迷茫,总结一下:
1.pyhton里所有的东西都是对象,即class也是一个对象,java里的class虽然也是一个Class的实例,但基本上是一个数据和函数的集合体,是不放具体东西的,但python不一样,不一样的地方如下:
a. python里所有对象可以动态地添加新的属性,当类动态地添加属性后,类的实例都能访问到该对象,其实这个很好理解,动态语言,只要遵循一定的解析规则就行
b. 类里的变量不是以self,开头定义的都是类变量,相当于java,c++里的static,所有实例共享他们
c.函数都是实现为descriptor
d.每个实例有__dict__用来存放动态的属性
e.继承:当继承后,python不会向java,c++那样在子类的实例中包含父类的实例,子类的实例是个全新的对象,与父类一点关系都没有,不会包含有父类的任何东西,继承只是在子类的__base__指向了父类,在查找函数,属性的过程中会查找父类,仅此而已,而这个父类也是class对象


2 python为每一个对象预定义了一些属性和方法:.
>>> Class1.__doc__ # 类型帮助信息
'Class1 Doc.'
>>> Class1.__name__ # 类型名称
'Class1'
>>> Class1.__module__ # 类型所在模块
'__main__'
>>> Class1.__bases__ # 类型所继承的基类
(<type 'object'>,)
>>> Class1.__dict__ # 类型字典,存储所有类型成员信息。
<dictproxy object at 0x00D3AD70>
>>> Class1().__class__ # 类型
<class '__main__.Class1'>
>>> Class1().__module__ # 实例类型所在模块
'__main__'


3 python的操作符重载以及更多
a. 操作符重载:这一点python与java差不多,通过重载特殊的函数来实现,重载时需要记住函数的名字
b. python做的更多,还可以改变attribute的get和set,默认是对__dict__进行操作,但你可以进行改变,具体的规则:(http://www.network-theory.co.uk/docs/pylang/Customizingattributeaccess.html)
__getattr__(self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).
__setattr__(self, name, value)
Called when an attribute assignment is attempted.
__getattribute__(self, name)
Called unconditionally to implement attribute accesses for instances of the class.
c  descriptor
python可以做的更多,当你获取到一个属性时,可以调用一个事先定义的函数,这个函数对属性进行操作,将操作的结果返回给你,python所有的函数都是descriptor,当通过实例访问函数时,descriptor将self插入参数列表,并且调用这个函数(http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#id836155)


4.python的多重继承
由于python的继承主要是将几个对象建立关系,因此多重继承最重要的就是怎样在多个父类中寻找某个attribute,具体参考http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#id836155


5.python寻找attribute的顺序:
If attrname is a Python-provided attribute for objectname, return it.
Check objectname.__class__.__dict__ for attrname. If it exists and is a data-descriptor, return the descriptor result. Search all bases of objectname.__class__ for the same case.
Check objectname.__dict__ for attrname, and return if found. Unless objectname is a type object, in which case search its bases too. If it is a type object and a descriptor is found in the object or its bases, return the descriptor result.
Check objectname.__class__.__dict__ for attrname. If it exists and is a non-data descriptor, return the descriptor result. If it exists, and is not a descriptor, just return it. If it exists and is a data descriptor, we shouldn't be here because we would have returned at point 2. Search all bases ofobjectname.__class__ for same case.

Raise AttributeError




原创粉丝点击