python入门3-面向对象

来源:互联网 发布:剑三捏脸数据免费 编辑:程序博客网 时间:2024/05/22 10:51

构造方法

# coding=utf-8class Person:    i = 10    def eat(self):        print "hello world"zhangsan = Person()zhangsan.eat()# hello worldclass P:    # def __init__(self):    #     print "构造方法,创建对象"    def __init__(self,x):        print "构造方法,创建对象,x="+x    def eat(self, x , y):        print x+yP('a').eat(1,2)# 构造方法,创建对象,x=a# 3


类方法、私有方法

# coding=utf-8class Person:    # 类方法    def eat(self):        print "吃饭"        self.__sleep()    # 私有方法(双下划线开始,只能内部调用)    def __sleep(self):        print "睡觉"zs = Person()zs.eat()# zs.__sleep()   调用不到

类属性、私有属性

class Person:    # 类属性    i = 10    # 私有属性(双下划线开始,只能内部使用)    __j = 20


内置属性
__name__ 类的名字

__doc__ 类的文档字符串

__bases__ 类的所有父类组成的元组

__dict__ 类的属性组成的字典

__module__ 类所属的模块

__class__ 类对象的类型


多继承

class Run3000:    def run(self):        print "run3000"class Jump3:    def jump(self):        print "jump3"#多继承class Sport(Run3000 , Jump3):    passsport = Sport()sport.run() #run3000sport.jump() #jump3


class Father:    def __init__(self):        print "father init"    def teach(self):        print "father teach"class Son(Father):    def teach(self):        print "son teach"zs = Son()  # father initzs.teach()  # son teach

如果父类构造带参,则子类可以通过super调用父类方法,也可以不掉用只重写,或者Son("hello")

#新式类 newstyle python3.5不需要写objectclass Father(object):    def __init__(self,i):        print "father init "+i    def teach(self):        print "father teach"class Son(Father):    def __init__(self):        super(Son,self).__init__("hello")    def teach(self):        print "son teach"zs = Son()  # father initzs.teach()  # son teach


封装

……


多态

……


面向对象编程

test1.py

class User:    def drive(self,Car):        Car.run()class Car:    def run(self):        print "car run"


test2.py  import导入的是模块,调用的时候需要“模块点”

import test1 as tbmw = t.Car()zs = t.User()zs.drive(bmw)


test3.py from导入的是具体类和方法,调用的时候直接调用

from test1 import User as ufrom test1 import Carbmw = Car()zs = u()zs.drive(bmw)


异常处理
def test(x,y):    print x/ytry:    test(1,0)except ZeroDivisionError:    print "run error: zero division"except :    print "run error"else:    print "run success"finally:    print "finally"

自定义异常

class NameNotFound(Exception):    def __init__(self):        print "not found name"def test(x):    if x == 0 :        raise NameNotFound

文件和流

# coding=utf-8f = open("text.txt","r+")print f.read()f.close()f = open("text-w.txt","w")f.write("hello")f.close()import os# os.remove("text-w.txt") # 删除文件# os.mkdir("bf") # 创建文件夹# os.rmdir("bf") # 删除文件夹print os.getcwd() # 获取当前路径


原创粉丝点击