Python面向对象编程(1)

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

注意在类外直接添加属性,只是会增加实例对象的属性,不会增加类的属性

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值