Python基础:一起来面向对象 (一)
类,一群有着相同属性和函数的对象的集合
class Document():
def __init__(self, title, author, context):
print('init function called')
self.title = title
self.author = author
self.__context = context # __ 开头的属性是私有属性 def get_context_length(self):
return len(self.__context) def intercept_context(self, length):
self.__context = self.__context[:length] harry_potter_book = Document('Harry Potter', 'J. K. Rowling', '... Forever Do not believe any thing is capable of thinking independently ...') print(harry_potter_book.title)
print(harry_potter_book.author)
print(harry_potter_book.get_context_length()) harry_potter_book.intercept_context(10) print(harry_potter_book.get_context_length()) print(harry_potter_book.__context) ########## 输出 ########## init function called
Harry Potter
J. K. Rowling
77
10 ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-b4d048d75003> in <module>()
22 print(harry_potter_book.get_context_length())
23
---> 24 print(harry_potter_book.__context) AttributeError: 'Document' object has no attribute '__context'
三问对象
1.如何在一个类中定义一些常量,每个对象都可以方便访问这些常量而不用重新构造?
答: 一般写成大字,与函数并列声明并赋值,注意是可以修改的。
2.如果一个函数不涉及到访问修改这个类的属性,而放到类外面有点不恰当,怎么做才能更优雅呢?
答: classmethod装饰器声明函数为类函数,最常用的功能用于定义不同的init函数,如create_empty_book函数创建的对象 context一定为'nothing',这比直接构造要清晰一些.
staticmethod装饰器声明函数为静态函数,可以用来做一些简单独立的任务
class Document():
WELCOME_STR = 'Welcome! The context for this book is {}.'
def __init__(self, title, author, context):
print('init function called')
self.title = title
self.author = author
self.__context = context
# 类函数
@classmethod
def create_empty_book(cls, title, author):
return cls(title=title, author=author, context='nothing')
# 成员函数
def get_context_length(self):
return len(self.__context)
# 静态函数
@staticmethod
def get_welcome(context):
return Document.WELCOME_STR.format(context)
empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove')
print(empty_book.get_context_length())
print(empty_book.get_welcome('indeed nothing'))
######### 输出 ##########
init function called
7
Welcome! The context for this book is indeed nothing.
3.既然类是一群相似的对象的集合,那么可不可以是一群相似的类的集合呢?
- 继承类在生成对象时不会自动调用父类的构造函数,必须在init()函数中显式调用父类中的构造函数 Entity.__init__(self, 'document')
- 当子类对象调用 get_context_length 函数时,如果没有实现此函数,会抛出get_context_length not implemented异常,这就使子类必须实现此函数。
- 父类中的print_title 函数体现了继承的优势,减少重复代码.
class Entity():
def __init__(self, object_type):
print('parent class init called')
self.object_type = object_type def get_context_length(self):
raise Exception('get_context_length not implemented') def print_title(self):
print(self.title) class Document(Entity):
def __init__(self, title, author, context):
print('Document class init called')
Entity.__init__(self, 'document')
self.title = title
self.author = author
self.__context = context def get_context_length(self):
return len(self.__context) class Video(Entity):
def __init__(self, title, author, video_length):
print('Video class init called')
Entity.__init__(self, 'video')
self.title = title
self.author = author
self.__video_length = video_length def get_context_length(self):
return self.__video_length harry_potter_book = Document('Harry Potter(Book)', 'J. K. Rowling', '... Forever Do not believe any thing is capable of thinking independently ...')
harry_potter_movie = Video('Harry Potter(Movie)', 'J. K. Rowling', 120) print(harry_potter_book.object_type)
print(harry_potter_movie.object_type) harry_potter_book.print_title()
harry_potter_movie.print_title() print(harry_potter_book.get_context_length())
print(harry_potter_movie.get_context_length()) ########## 输出 ########## # Document class init called
# parent class init called
# Video class init called
# parent class init called
# document
# video
# Harry Potter(Book)
# Harry Potter(Movie)
#
#
抽像类的使用
抽象类是为父类而生的,不能对象化。如果有抽象函数也必须在子类中重写才能使用。
from abc import ABCMeta, abstractmethod class Entity(metaclass=ABCMeta):
@abstractmethod
def get_title(self):
pass @abstractmethod
def set_title(self, title):
pass class Document(Entity):
def get_title(self):
return self.title def set_title(self, title):
self.title = title document = Document()
document.set_title('Harry Potter')
print(document.get_title()) entity = Entity() ######### 输出 ##########
Harry Potter ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-266b2aa47bad> in <module>()
21 print(document.get_title())
22
---> 23 entity = Entity()
24 entity.set_title('Test') TypeError: Can't instantiate abstract class Entity with abstract methods get_title, set_title
参考:
极客时间《Python核心技术与实战》
Python基础:一起来面向对象 (一)的更多相关文章
- python基础整理4——面向对象装饰器惰性器及高级模块
面向对象编程 面向过程:根据业务逻辑从上到下写代码 面向对象:将数据与函数绑定到一起,进行封装,这样能够更快速的开发程序,减少了重复代码的重写过程 面向对象编程(Object Oriented Pro ...
- python基础-9.1 面向对象进阶 super 类对象成员 类属性 私有属性 查找源码类对象步骤 类特殊成员 isinstance issubclass 异常处理
上一篇文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用(可以讲多函数中公用的变量封装到对象中) 对象 ...
- python基础篇_006_面向对象
面向对象 1.初识类: # 定义一个函数,我们使用关键字 def """ def 函数名(参数): '''函数说明''' 函数体 return 返回值 "&qu ...
- python基础学习 Day19 面向对象的三大特性之多态、封装 property的用法(1)
一.课前内容回顾 继承作用:提高代码的重用性(要继承父类的子类都实现相同的方法:抽象类.接口) 继承解释:当你开始编写两个类的时候,出现了重复的代码,通过继承来简化代码,把重复的代码放在父类中. 单继 ...
- python基础学习 Day19 面向对象的三大特性之多态、封装
一.课前内容回顾 继承作用:提高代码的重用性(要继承父类的子类都实现相同的方法:抽象类.接口) 继承解释:当你开始编写两个类的时候,出现了重复的代码,通过继承来简化代码,把重复的代码放在父类中. 单继 ...
- python基础学习Day17 面向对象的三大特性之继承、类与对象名称空间小试
一.课前回顾 类:具有相同属性和方法的一类事物 实例化:类名() 过程: 开辟了一块内存空间 执行init方法 封装属性 自动的把self返回给实例化对象的地方 对象:实例 一个实实在在存在的实体 组 ...
- python基础笔记之面向对象
# class Foo:# name="kevin"## def __init__(self,puppy):# self.tomato= 'red'# self.dog = pup ...
- python基础——18(面向对象2+异常处理)
一.组合 自定义类的对象作为另一个类的属性. class Teacher: def __init__(self,name,age): self.name = name self.age = age t ...
- python基础学习笔记——面向对象初识
面向对象初识 python中一切皆对象. 类有两种: 新式类:在py3中所有类都是新式类 经典类:在py2中只有类本身继承了object类才叫做新式类,默认是经典类 class Person: cou ...
- python基础——17(面向对象)
一.名称空间 名称空间有内置名称空间,全局名称空间,局部名称空间.它是用来存放名字与值对应关系的地方. test.py文件: num = 10 def fn(): print("fn run ...
随机推荐
- Leetcode 142.环形链表II
环形链表II 给定一个链表,返回链表开始入环的第一个节点. 如果链表无环,则返回 null. 说明:不允许修改给定的链表. 进阶:你是否可以不用额外空间解决此题? 链表头是X,环的第一个节点是Y,sl ...
- 牛客网暑期ACM多校训练营(第二场)B discount
链接:https://www.nowcoder.com/acm/contest/140/B来源:牛客网 题目描述 White Rabbit wants to buy some drinks from ...
- Codeforces Round #304 (Div. 2)-D. Soldier and Number Game,素因子打表,超时哭晕~~
D. Soldier and Number Game time limit per test 3 seconds memory limit per test 256 megabytes input s ...
- hdu 5044 树链剖分
转载:http://blog.csdn.net/qinzhenhua100/article/details/39716851 二种操作,一种更新结点值,一种更新路径值,最后输出更改后的结点值和路径值. ...
- SOJ 2749_The Fewest Coins
[题意]:已知整个交易系统有N (1 ≤ N ≤ 100)种不同的货币,分别价值V1,V2,V3.......VN(1 ≤ Vi ≤ 120),FJ分别有C1,C2,C3.....CN(0 ≤ Ci ...
- codevs——1080 线段树练习
1080 线段树练习 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 题目描述 Description 一行N个方格,开始每个格子里都有 ...
- 洛谷 P1081 开车旅行(70)
P1081 开车旅行 题目描述 小AA 和小BB 决定利用假期外出旅行,他们将想去的城市从 11到 NN 编号,且编号较小的城市在编号较大的城市的西边,已知各个城市的海拔高度互不相同,记城市 ii的海 ...
- how to read openstack code : wsgi
要读懂本篇,你至少得写过一个python的web程序,并且把它部署到web服务器上过. 什么是wsgi 假设你写了一个python的web程序,并部署到了nginx上,那么一个http request ...
- 开放-封闭"原则(OCP)
Open-Closed Principle原则讲的是:一个软件实体应当对扩展开放,对修改关闭. 优点: 通过扩展已有软件系统,可以提供新的行为,以满足对软件的新的需求,使变化中的软件有一定的适应性和灵 ...
- field load respone data
问题: AJAX 使用谷歌浏览器 POST 请求报如下错误 field load respone data 使用 火狐 浏览器就正常 调试1: 发现其实我请求的回调函数能打印出来数据,但是,在netw ...