Python基础 第7章 再谈抽象

1. 1 多态

多态,即便不知道变量指向的是哪种对象,也能对其执行操作,且操作的行为将随对象所属的类型(类)而异。

1.2 多态与方法

当无需知道对象是什么样的就能对其执行操作时,都是多态在起作用。

1 # 使用random模块种的choice函数,随机从序列中选择一个元素
2 from random import choice
3 x = choice(['Hello world!', [1, 2, 'e', 'e', 4]])
4 
5 print(x.count('e'))
6 
7 结果:1

1.3 封装

封装是指,向外部隐藏不必要的细节。

封装不同于多态,多态让你无需知道对象所属的类(对象的类型)就调用其方法,而封装让你无需知道对象的构造就能使用它。

1.4 继承

 

2. 类

每个对象都属于特定的类,并被称为该类的实例。在Python中,约定使用英语单数并将首字母大写表示类,如Bird和Lark。

2.1 创建自定义类

 1 # 创建自定义类
 2 class Person:
 3 
 4     def set_name(self, name):
 5         self.name = name
 6 
 7     def get_name(self):
 8         return self.name
 9 
10     def greet(self):
11         print("Hello, World! I'm {}.".format(self.name))
12 
13 foo = Person()
14 foo.set_name('Luke Skywallker')
15 print(foo.greet())
16 
17 结果:
18 Hello, World! I'm Luke Skywallker.
19 None

 

3 属性、函数和方法(不是很懂)

方法和函数的区别表现在前一节提到的参数self上。

方法(或者说是 关联的方法)将其第一个参数关联到它所属的实例,因此无需提供这个参数。

 1 class Class:
 2     def method(self):
 3         print('I have a self!')
 4 
 5 def function():
 6     print("I don't know....")
 7 
 8 instance = Class()
 9 # print(instance.method()) # 为什么会连续打印两个结果1)I have a self! 2)None
10 instance.method()
11 instance.method = function
12 instance.method()
4 再谈隐藏
# 将属性定义为私有,私有属性不能从对象外部访问,只能通过存取器方法(如get_name和set_name)来访问
# 要让方法或属性成为私有的(不能从外部访问),只需让其名称以两个下划线打头即可
 1 class Secretive:
 2     def __inaccessible(self):
 3         print("Bet you can't see me...")
 4 
 5     def accessible(self):
 6         print("The secret message is: ")
 7         self.__inaccessible()
 8 
 9 s = Secretive()
10 # s.__inaccessible() 报错如下:
11 # Traceback (most recent call last):
12 #   File "D:/Python/PycharmProjects/untitled1/venv/Robots_learning.py", line 1619, in <module>
13 #     s.__inaccessible()
14 # AttributeError: 'Secretive' object has no attribute '__inaccessible'
15 
16 s.accessible() #结果如下:
17 # The secret message is:
18 # Bet you can't see me...

 

posted @ 2019-09-03 08:46  ElonJiang  阅读(200)  评论(2编辑  收藏  举报