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"
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() # 获取当前路径
阅读全文
0 0
- python入门3-面向对象
- PYTHON面向对象入门
- python面向对象入门
- Python一天入门16:面向对象的编程3-继承
- 入门python--类与面向对象(3)
- python 面向对象入门 - 之 正则表达式
- python 面向对象入门 - 之 Web Service
- python 面向对象入门 - 之 单元测试
- Python入门:面向对象编程-封装
- python入门6面向对象高级编程
- java入门(3)--面向对象
- Python一天入门14:面向对象的编程1-对象
- Python 3面向对象编程
- Python面向对象学习(3):
- Python 面向对象(3)
- python面向对象编程(3)
- python入门系列12―——面向对象
- python入门(二十七):面向对象之封装
- 基本日期数据类型
- 图像
- 简洁版图文介绍maven本地仓库配置和在eclipse中的配置
- Python实现双向链表的基本操作
- jQueryEasyUI
- python入门3-面向对象
- 使用setup轻松解决VMware虚拟机Linux -CentOS系统 NAT连网问题
- 在活动中使用Menu菜单
- KVM
- chapter4:内容过滤及分类---基于物品属性的过滤
- springmvc的理解下
- spring入门篇二(1)
- C语言实验——某年某月的天数
- shuffle性能调优之HashShuffleManager和SortShuffleManager