Python面向对象编程

python

#encoding=utf-8
"""
Python学习笔记二十---- 对象高级
1. 内部类:
所谓的内部类,就是在类的内部定义的类,主要目的是更好的抽象现实世界,一般不赞同使用内部类,会使程序结构复杂,但是理解内部类有助于理解模块的调用

内部类实例化方法:

方法一:直接使用外部类调用内部类,格式为:
     object_name=outclass_name.inclass_name()
     outclass_name是表示外部类的名称,inclass_name表示内部类的名称,object_name表示内部类的示例


方法二: 先对外部类进行实例化,然后在实例化内部类。格式为:
    out_name=outclass_name()
    in_name=out_name.inclass_name()
    in_name.method()
    out_name()表示外部类的示例,in_name表示内部类的示例
"""


-------------------------------<<<eg1>>>--------------------------------
#!/usr/bin/python
#encoding=utf-8

class Auto:
    class Site:        #内部类
        def status(self):
            print "地盘的状态"
    class Wheel:
        def run(self):
            print "轮子在跑"

if __name__ ==__"main"__:
    car=Auto.Site()    #方法一 car=外部类.内部类()
    car.status()

    car=Auto()         #方法二:外部类实例化
    car2=car.Wheel()   #内部类实例化
    car2.run()         #内部类调用方法

"""
输出结果为:
[jane@redhat class]$ python 5.py
>>>地盘的状态
>>>轮子在跑
[jane@redhat class]$
"""


-------------------------------<<<eg2>>>--------------------------------
#!/usr/bin/python
class A:    
    x=10
    class Aa:    # 定义内部类
        y=20

objc=A.Aa()      #方法1,实例化内部类,这时候只能调用到内部类中y的值

obja=A()         #方法2,先实例化外部类
objaa=obja.Aa()  #再实例化内部类
print objaa.y    #通过内部类调用y的值
print obja.x     #通过外部类调用x的值

del obja         #显示的析构
del objaa

输出为:
[jane@redhat class]$ python c5.py
>>>20
>>>10
[jane@redhat class]$


"""
2.构造函数和析构函数
a)构造函数
用于初始化类的内部状态,python提供的构造函数是__init__();__init__()方法是可选的,如果不提供的话,python就会给出一个默认的__init__方法.

一般对数据的获取需要自定义get和set方法

b)析构函数
用于释放对象占用的资源,python提供的析构函数是__del__();__del__()也是可选的,如果不提供的话,python则会在后台提供默认的析构函数。

如果要显示的调用析构函数,可以使用del关键字,方式如下:
del 对象名
"""


------------------------------<<<构造函数>>>------------------------------
#!/usr/bin/python
#encoding=utf-8
#构造函数
class Auto:
    def __init__(self,color):   #构造函数,初始化color
        self.__color=color
        print self.__color

    def getColor(self):
        print self.__color

    def setColor(self,color):
        self.__color=color
        print self.__color

if __name__ == '__main__':
    color="blue"
    car=Auto(color)           #输出为bule

    car.getColor()            #调用getColor方法,输出为:blue

    car.setColor("red")       #调用setColor方法,输出为:red
    car.getColor()            #在次调用getColor的时候,self.color已经为red了,所以输出为red


------------------------------<<<析造函数>>>------------------------------
#!/usr/bin/python
#encoding=utf-8
#析构函数

class Auto:
    def __init__(self,color):
        self.__color=color
        print self.__color

    def __del__(self):           #定义析够函数,但是析构函数会在所有函数最后执行
        self.__color="aa"
        print self.__color
        print "Release..."

    def getColor(self):
        print self.__color

color="blue"
car=Auto(color)   #实例化,输出为blue
car.getColor()    #首先调用getColor方法, 执行print self.__color得输出结果blue,如果在这里,
                  #所有的程序都执行完后,将执行del析够函数,print “Release”,这时的self.__color应该是"aa"  

#car.getColor()   # 在所有的函数中,析够函数是放在最后面执行的,因此这个调用还是应该在析函数前执行~                                                                                 
"""
输出为:
[jane@redhat class]$ python 7.py
>>>blue
>>>blue
>>>aa
>>>Release...
[jane@redhat class]$
"""

"""
3.垃圾回收机制

python采用垃圾回收机制来清理不在使用的对象,python提供gc模块释放不再使用的对象。

python采用“引用计数”的算法方式来处理回收,即:当某个对象在其作用域内不再被其他对象引用的时候,python就会自动清楚对象;

Python的函数collect()可以一次性收集所有待处理的对象(gc.collect())

步骤:先导入模块gc, 然后是对象,最后gc.collect()

4.常见的内置方法

__init__(self,...)-----初始化对象,创建对象时调用(实例化对象时)

__del__(self,...)------释放对象,在对象被删除时调用

__new__(cls,*args.**kwd)----实例的生成

__str__(self)----------在使用print时调用,将内容转换为字符串

__getitem__(self,key)----获取序列的索引key所对应的值

__len__(self)------------调用内敛函数len时候调用的是它  ##什么意思?

__cmp__(src,dst)---------比较

__getattr__(s,name)------ 获取属性的值

__setattr__(s,name,val)---设置属性的值

__delattr__(s,name)-------删除name的属性

__getattribute__()--------与 __getattr__ 类似

__gt__(self,other)--------判断self对象是否大于other 对象

__lt__(self,other)--------判断self对象是否小于other 对象

__ge__(self,other)--------判断self对象是否大于或等于other 对象

__le__(self,other)--------判断self对象是否小于或等于other 对象

__eq__(self,other)--------判断 self 对象是否等于 other 对象

__call__(self,*args)------把实例对象作为函数调用


下面针对内置函数中的几个做详细的介绍:

a) __new__()
说明:__new__()在__init__之前被调用,用于生成实例对象

用途:主要用于设计模式中的单例模式

单例模式:是指创建唯一对象,单例模式设计的类只能实例化一个对象
"""


------------------------------<<<eg: __new__()的用法>>>------------------------------
#encoding=utf-8

class Singleton(object):      #定义一个新型类
    __instance=None           #定义一个私有属性
    def __init__(self):
        self.color="red"

    def __new__(cls,*args,**kwd):
        if Singleton.__instance is None:
            Singleton.__instance=object.__new__(cls,*args,**kwd)
            print "this is new example"
#这一段__new__(),先判断类的属性是否是空,如果是,在调用类的__new__方法 打印"this is new example",然后才能调用__init__.如果这里的条件不成立,则不会调用init方法
        return Singleton.__instance

c1=Singleton()    #将类实例化,在这之前将输出"this is new example",然后执行__init__后
print c1.color   #执行了__init_ 后,打印self.color的之,就相当与在__init__中增加一句print self.color
#c2=Singleton()
#print c2.color

#c3=Singleton()
#print c3.color

"""
输出结果:
[jane@redhat class]$ python 8.py
>>>this is new example
>>>red
[jane@redhat class]$
"""
"""
b)__getattr__(), __setattr__(),__getattribute__()
说明:在程序中,
当读取对象的某个属性时,python会自动调用__getattr__()方法得到属性的值;当使用赋值语句的时,python会自动调用__setattr()方法设置属性的值。

__getattribute__()方法和__getattr__()方法的功能一样,只是前者能好的控制,代码更强壮

另外请注意: python中不存在__setattribute__()方法
"""


------------------------------<<<eg:综合>>>------------------------------
#encoding=utf-8

class Fruit(object):                    #定义新型类

    def __init__(self, color = "red", price = 0):       #初始化,给了三个参数
        self.__color = color
        self.__price = price

    def __getattribute__(self, name):                   # 获取属性值的方法
        return object.__getattribute__(self, name)

    def __setattr__(self, name, value):                 #设置属性值的方法
        self.__dict__[name] = value

if __name__ == "__main__":
    fruit = Fruit("blue", 10)                       #实例化
    print fruit.__dict__.get("_Fruit__color")       #获得color的属性,注意这里使用__dict__特殊属性来获取color的属性值
    fruit.__dict__["_Fruit__price"] = 5             #设置属性值
    print fruit.__dict__.get("_Fruit__price")       #获得price的属性值

"""
输出为:
[jane@redhat class]$ python 10.py
>>>blue
>>>5
[jane@redhat class]$

总结:这个示例其实就需要注意一点特殊属性__dict__的用法,其他的就好理解了
"""

转自https://blog.163.com/qimeizhen8808@126/blog/static/16511951820127220173667/

Leave a Comment