python--面向对象

一、类的定义(在类名后加(object)为新式类,推荐写上)

 1 class 类名:
 2     #属性
 3     
 4     #方法
 5     def 方法名(self):
 6         方法内容
 7 
 8 #创建一个对象
 9 example = 类名()
10 #方法的调用
11 example.方法名()
类的定义

  1.python类的初始化:

1 class Cat:
2     def __init__(self):
3         print(111)
4     def test(self):
5         print(aaa)
构造方法

  2.魔术方法:__str__(self)(相当于php的__call方法),在函数外部打印时自动调用

  3.私有方法:__方法名

  4.__del__(self):删除一个对象时,自动调用(相当于php的析构方法)

  5.__new__(cls):负责创建对象,__new__和__init__相当于分担了构造方法的职责__new__只负责创建对象,__init__只负责初始化对象,详看:http://blog.csdn.net/four_infinite/article/details/52798919

  6.property的使用,相当于php中的__get和__set魔术方法,用法见下例

class Test(object):
    def __init__(self):
        self.__num = 100

    def setNum(self, newNum):
        self.__num = newNum

    def getNum(self, newNum):
        return self.__num

    num = property(getNum, setNum)

t = new Test()
t.num = 200
print(t.num)    #结果为:200
property的使用
class Test(object):
    def __init__(self):
        self.__num = 100

    @property
    def num(self):
        return self.__num

    @num.setter
    def num(self, newNum)
        self.__num = newNum
property的使用二

   7.__slots__('name', 'age'):使用该魔术变量后只能允许往类中添加name和age属性,不允许添加其他

  8.像对象中添加实例方法

import types

实例化的对象.实例方法 = types.MethodType(方法名, 实例化的对象)
像对象中添加实例方法

 

二、类的继承

1 class Animal:
2     def eat(self):
3         print('我正在吃东西')
4 
5 class Dog(Animal):
6     def drink(self):
7         print('我正在喝东西')
类的继承

  1.在子类中调用父类

    (1)直接使用父类的类名加方法名:father.方法名(self)

    (2)super().方法名()

  2.所有私有方法、属性不会被继承

  3.python支持多继承:class C(A,B):

  4.类名.__mro__可以查看在继承中方法调用的顺序

三、类方法

1 class People(object):
2     country = 'china'
3     
4     @classmethod
5     def getCountry(cls):
6         return cls.country
类方法的定义

类方法、属性可以用类名直接调用

四、静态方法

 1 class People(object):
 2     country = 'china'
 3 
 4     @staticmethod
 5     #静态方法
 6     def getCountry():
 7         return People.country
 8 
 9 
10 print People.getCountry()
静态方法的定义
 五、单例模式
1 class Dog(object):
2     __instance = None
3 
4     def __new__(cls):
5         if cls.__instance == None:
6             cls.__instance = object.__new__(cls)
7             return cls.__instance
8         else:
9             return cls.__instance
单例模式

六、异常处理

  1.捕获异常

 1 try:
 2     #代码内容
 3 except Exception(获异常具体的名字) as res:
 4     #捕获到异常要执行的操作
 5     print(res)
 6     raise    #抛出异常
 7 else:
 8     print('没有异常才会执行')
 9 finally:
10     print('最后执行的代码')
捕获异常
posted @ 2017-12-31 22:15  Leur  阅读(179)  评论(0编辑  收藏  举报