1.函数基本
可继承父类
本身定义的方法会覆盖父类的方法
新式类是有父类的,经典类是没有父类的。
(Python3都是新式类)
区别:
1.__slots__
新式类有,
对属性有限制
#__slots__=('x','y')
限制类只有x、y两个属性
2.继承顺序
新式类引入了继承,super
3.__new__
4.__getattribute__
“””
三引号里面的内容会加入到类的帮助里面去
“”“
2.实例属性/类属性
class Car(object):
#类属性
country=u'中国'
def __init__(self,length,width,height,owner=None):
#以下属于实例属性
self.owner=owner
self.length=length
self.width=width
self.height=height
#如果在实例属性中有,类的对象调用时,就先用实例属性。没有的话,就调用类的属性
self.country='china'
a=A(1,2,3)
删掉属性:
del a.country
3.类的私有属性
只有类可访问
类似于Java的
private
用法:
不可以直接访问
self.__xxx
可以直接访问,但是访问时,自己提醒自己,这个属性不能直接访问
self._xxx
4.init
在类实例化的时候自动被调用
5.描述符
一个定义了set和get的对象
关键词:property
把方法当做属性访问
class Car(object):
#类属性
country=u'中国'
def __init__(self,length,width,height,owner=None):
#以下属于实例属性
self.__owner=owner
self.length=length
self.width=width
self.height=height
@property
def owner(self):
return self.__owner
@owner.setter
def owner(self,value):
self.__owner=value
@owner.deleter
def owner(self):
self.__owner=None
6.getattr
#在__dict__和_class__dict__中没有找到相应的变量的时候,就会调用
def __getattr__(self,name):
if name=='a':
return 'a'
else:
return self.__dict__.get(name,None)
#只要是赋值,都会调用此方法,包括在__init__中
def __setattr__(self,name,value):
pass
def __delattr__(self,name):
pass
7.slots
例如:
slots=[‘length’]
表明了这个类有’length’这个实例属性,可以使用。
当slots和setattr尽量不要一起用,需要注意:
不确定,有待研究:
如果用setattr来给实例属性赋值,那么这些实例属性可以在类的内部使用,但是这个实例属性是不能够直接访问的,只能通过getattr来访问。
但是不在slots里面的属性也会去调用getattr,可以通过
assert name in self.slots, “not have this attribute”
来屏蔽对不在slots里面的属性的访问
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke
class Car(object):
country = u'中国'
__slots__=('length','width','height','owner','__dict__')
def __init__(self, length, width, height, owner=None):
self.owner = owner
self.length = length
self.width = width
self.height = height
def __getattr__(self,name):
print "__getattr__",name
# assert name in self.__slots__, "Not have this attribute "+name
return self.__dict__.get(name,'None')
def __setattr__(self,name,value):
pass
print "__setattr__",name
# assert name in self.__slots__, "Not have this attribute "+name
if name!='owner':
assert value>0, name+" must larger than 0"
self.__dict__[name]=value
def __delattr__(self,name):
print "__delattr__",name
# assert name in self.__slots__, "Not have this attribute "+name
if name=='owner':
self.__dict__[name]=None
if __name__ == '__main__':
a = Car(1.2,1.4,1.5,u'黑板客')
"""
print a.owner
del a.owner
print a.owner
a.length=1
print a.country
a.country = 'china'
print a.country
a.name = u"一汽"
"""
用getatrr(a,’length’)来访问,
经常用于动态访问(在不确定的时候)对象或属性