zoukankan      html  css  js  c++  java
  • Python面向对象编程

    1.类的定义:

    class <类名>:
        <其他语句>
    class <类名>(父类名):
        <其他语句>

    例如:

    class Father:
        _age=22
        _name="sunny"
    class Son(Father):
        _work="IBM"
    son=Son()
    print(son._name)
    print(son._work)

    运行结果:

    //结果
    sunny
    IBM

    2.如果直接使用类名修改其属性,那么将影响那些没有改变此属性值的已经实例化的对象的该属性值。

    有点绕,举个例子:

    class Sample:
        _attribute=88
    
    sample1=Sample()
    sample1._attribute=66
    
    sample2=Sample()
    
    print(sample1._attribute)
    print(sample2._attribute)
    
    //使用类名称修改_attribute这个属性的值
    Sample._attribute=6868
    print(sample1._attribute)
    print(sample2._attribute)

    运行结果:

    //结果
    66
    88
    66
    6868

    由此可知,对于sample1对象,由于修改了他的_attribute属性的值(改为66),所以在执行Sample._attribute=6868后,并不会改变sample1的这个属性值。

    但是对于sampe2,可以发现使用类名.的方式改变了属性值,会影响到已经实例化的对象。

    这一点和Java很不一样,因为在Java中无法使用类名.的形式修改非静态变量。换句话讲,若_attribute为静态变量(在Java中,在Python中无静态变量),通过sample1修改了这个变量,那么sample2的这_attribute变量也会改变。static变量嘛,你懂得。只有一份。

    综上,可知。Python的语法很不同,要注意。

    3.类的属性:

    如果类的属性是以两条下划线开始则该属性为类的私有属性,不能在类外部被访问。

    例如这样就会出错:

    class Tom:
        __name=''
        __age=0
        school='MIT'
        
    tom=Tom()
    print(tom.__age)   #这里如果这样写就不会报错:   print(tom.school)     因为__name是私有变量,而school是public的。所以可以直接调用

    出错显示:

    Traceback (most recent call last):
      File "F:workspaceFirstPythonProgramsrccomwjypythonClient.py", line 7, in <module>
        print(tom.__age)   
    AttributeError: 'Tom' object has no attribute '__age'

    私有属性的命名形式: __privateAttrs

    如果在类内部的方法中使用类的私有属性,则应该以如下方式调用。

    self.__privateAttrs        #其实无论是类的私有变量(以__开头的)还是非私有变量(不以__开头的),在类内部的方法中使用都要以self.attributeName的形式使用。

                                       #这也是一种良好的编程习惯

    4.类的方法

    在类的内部使用def关键字可以为类定义一个方法。与函数定义不同的是,类的方法必须包含参数 'self ’ ,

    且'self'必须为第一个参数。和类的私有属性命名相同,类的私有方法名也要以两条下划线开始。

    注意:1.无论是私有变量还是public变量,类的私有方法都可以使用。类的非私有方法也可以使用类的私有变量和非私有变量。

            2.类的私有方法或者私有变量,不能通过类名.的形式调用。也不能通过实例化的对象调用,只能内部调用。

    例如:

    class ShowDetail:
        __name='Wjy'
        __school='MIT'
        work='IBM'
        def showName(self):
            print(self.__name)
        def __showWork(self):
            print(self.work)
    
    showDetail=ShowDetail()
    showDetail.showName()
    
    #ShowDetail.__showWork(ShowDetail)       这句会报错
    #showDetail.__showWork()                 这句也会报错

    注意: 在类的成员方法中调用别的成员方法,无论是私有的还是飞私有的方法。都要使用 self.方法名的形式。

           总之养成良好的编程习惯,使用类成员变量或者成员方法时,都是用  self. 的形式调用。(在java中,使用 this.)

    但是不能调用自己,比如下面这样写的话就会出错:

    class ShowDetail:
        __name='Wjy'
        __school='MIT'
        work='IBM'
        def showName(self):
            self.showName()
            print(self.__name)
        

    5

    在python中有一类以两条下划线开始并且以两条下划线结束的类方法,称之为专有方法。

    __init__  构造函数,生成对象时调用

    __del__  析构函数,释放对象时调用

    __add__ 加运算

    __mul__  乘运算

    __cmp__ 比较运算

    __repr__ 打印、转换

    __setitem__ 按照索引赋值

    __getitem__ 按照索引获取值

    __len__ 获得长度

    __call__ 函数调用

    例如:

    >>> class book:
    ...     __author = ''
    ...     __name = ''
    ...     __page = ''
    ...     price = 0
    ...     def __check(self,item):
    ...             if item == '':
    ...                     return 0
    ...             else:
    ...                     return 1
    ...     def show(self):
    ...             if self.__check(self.__author):
    ...                     print self.__author
    ...             else:
    ...                     print 'No value'
    ...             if self.__check(self.__name):
    ...                     print self.__name
    ...             else:
    ...                     print 'No value'
    ...     def setname(self,name):
    ...             self.__name = name
    ...     def __init__(self,author,name):
    ...             self.__author = author
    ...             self.__name = name
    ... 

    6.需要考虑一个问题,Python只有 private和非private成员方法和成员变量。但是没有protected的,那么在类的继承中子类不能继承private(以__开头的)成员变量和方法。

    比如:

    class Aa:
        __attributeA='a'
        attributeAA='aa'
    class Bb(Aa):
        def show(self):
            print(self.attributeAA)
            #print(self.__attributeA)    这句话运行会出错,private的是继承不到的。
    
    bb=Bb()
    bb.show()

    7.Python支持多重继承,注意Java是不支持的。而C++是支持的:

    class FatherA:
        attribute='a'
        def show(self):
            print(self.attribute)
    class FatherB:
        attribute='b'
        def show(self):
            print(self.attribute)
    class Son(FatherA,FatherB):
        
        def showAll(self):
            print('Attribute: '+self.attribute)
    son=Son()
    
    son.show()
    son.showAll()

    输出结果:

    a                                             //可知,默认都是输出的FatherA的,就是第一个的。若调整顺序class Son(FatherB,FatherA),则会输出FatherB的。
    Attribute: a

    8.重载

    8.1重载  +  运算符:

    代码:

    class Option:
        num=6
        def __add__(self,n):
            self.num+=n
            
    option=Option()
    option+5
    print(option.num)                                    #若改为print(Option.num)则会输出  6

    结果:

    //结果
    
    11                                                     //这样写是违法的:   Option+3

    8.2看个例子

    class MyList:
        mylist=[]
        def __init__(self,*args):
            for arg in args:
                self.mylist.append(arg)
                print(arg)
        def show(self):
            print(self.mylist)
    
    # list=[1,2,3,4,5]  
    # myList=MyList(list)      
    myList=MyList(1,2,3,4,5)
    myList.show()

    输出结果:

    1
    2
    3
    4
    5
    [1, 2, 3, 4, 5]

    若这样初始化对象:

    list=[1,2,3,4,5]
    myList=MyList(list

    则结果为:

    [1, 2, 3, 4, 5]
    [[1, 2, 3, 4, 5]]
  • 相关阅读:
    Spring+Hibernate集成后事务与Session的一些理解。
    对Spring的一些个人理解
    centos5.8 x86_64安装oracle10g
    C#中MessageBox用法大全(附效果图)
    解决SQL Server管理器无法连接远程数据库的问题
    【sql2000数据库】Named Pipes Provider error 40
    用SQL数据库批量插入数据简介
    DBGridEH在Delphi7中的安装方法及使用说明
    sql server中datetime字段只取年月日如20060421,默认值如何设置?getdate()得到的是包含时分秒的时间。
    获取 Windows 窗体 DataGridView 控件中选定的单元格、行和列
  • 原文地址:https://www.cnblogs.com/wangjiyuan/p/jibenyufa.html
Copyright © 2011-2022 走看看