1.Python中面向对象编程
1.1 私有属性和方法 前面两个下划线__
_下划线代表protected 方法
1.2 普通函数和类方法的区别是,类方法里必须带一个默认参数self,可以是其他的写法,self 代表的是类的实例
1.3 创建类对象,类的名称 来实例化,并通过 __init__ 方法接收参数,没有new, __init__相当于C++的构造函数, __del__相当于C++的析构函数
1.4 调用类的方法和属性,用成员运算符.
1.5 类的属性可以随时添加,不用在定义类的时候就写好
1.6 类中的方法有三种,实例方法,静态方法,类方法,我们只是说明实例方法
1.7 类的继承
class 派生类名(基类名)
看下具体代码
class Student:
def __init__(self,name,score):
self.__name=name
self.__score=score
def __del__(self):
del self.__name
del self.__score
print 'del is called'
def GetName(self):
return self.__getName()
def __getName(self):
return self.__name
def setName(self,name):
self.__name=name
wc=Student('zhc',100)
print wc.GetName()
wc.setName('gaohaijie')
print wc.GetName()
wc.age=30
print wc.age
zhc=Student('huaichao',40)
print zhc.age
输出结果如下:
zhc
gaohaijie
30
Traceback (most recent call last):
File "d:\py\PucDataService\test.py", line 40, in <module>
print zhc.age
AttributeError: Student instance has no attribute 'age'
del is called
del is called
注意在类外直接添加属性,只是会增加实例对象的属性,不会增加类的属性