《Python基础教程》读书笔记07-更加抽象

多态,封装,继承

class Class:  # 类
    def method(self):
        print ("self")
    def function():
        print ("function")

def func():  # 普通方法
    print ("func")

>>> x = Class()  # 对象
>>> x.method()
self
>>> x.function()  # 对象调用方法,需要有self参数(可以是别的名字)
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    x.funvtion()
TypeError: funvtion() takes 0 positional arguments but 1 was given

>>> Class.method()  # 当然 类名 也不能调用实例方法
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    Class.method()
TypeError: method() missing 1 required positional argument: 'self'

>>> Class.function()  # 类名 调用类方法
function
>>> x.function = func  # 将对象的方法,重新绑定到一个普通函数上
>>> x.function()
func

私有化

名字前面加双下划线,外部就无法访问了

class t:
    __name = "zhang"  # 名字前面加双下划线(方法也一样),外部就无法访问了
    def getname(self):
        return self.__name
    def setname(self,name):
        self.__name = name

>>> x = t()
>>> x.setname("xxxx")
>>> x.getname()
'xxxx'
>>> x.__name
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    x.__name
AttributeError: 't' object has no attribute '__name'
>>> x._t__name # 实际还是可以访问,但不要这么做(所有以双下划线开始的名字都被翻译成了前面加上单下划线和类名的形式)
'xxxx'

如果不要使用这种方法,又想要其他对象不要访问内部数据,可以使用单下划线(对象仍能访问),前面有下划线的名字都不会被带星号的 import 语句 from module import * 导入。

类的命名空间

class test:
    print ("class...test")  # 类加载 就运行
    number = 0  # 可供所以实例访问
    def init(self):
        test.number += 1  # 类名.变量名
    def testinit():  # 类方法,不能用 (实例.方法) 的形式访问
        test.number += 1

# class...test
>>> test.testinit()
>>> test.number
1
>>> x = test()
>>> x.init()
>>> x.number
2

继承

class Filter:
    def init(self):
        self.blocked = []
    def filter(self, seq):
        return [x for x in seq if x not in self.blocked]

class SPAMFilter(Filter):  # 继承的父类写在括号内
    def init(self):  # 重写父类方法
        self.blocked = ['SPAM']

检查继承

>>> issubclass(SPAMFilter, Filter)  # 检查 SPAMFilter 是不是 Filter 的子类
True
>>> issubclass(Filter, Filter)
True
>>> issubclass(Filter, SPAMFilter)
False

已知子类,查看父类

>>> Filter.__bases__  # 返回元组,如果有多个会都返回
(<class 'object'>,)
>>> SPAMFilter.__bases__
(<class '__main__.Filter'>,)

检查一个对象是否是一个类的实例

>>> s = SPAMFilter()
>>> isinstance(s, SPAMFilter)
True
>>> isinstance(s, Filter)
True
>>> isinstance(s, int)
False

查看一个对象所属的类

>>> type(s)
<class '__main__.SPAMFilter'>

多个超类

多重继承,避免使用
在括号内继续添加即可,用逗号分割。

必须要注意超类的顺序,先继承的类中的方法会重写后继承的类中的方法(写在前面的超类,优先级更高)

检查所需方法是否存在

>>> hasattr(s, 'init')
True
>>> hasattr(s, 'init2')
False

查看或设置对象的方法或变量

getattr 函数,可以在方法或变量不存在时提供默认值。setattr 函数可以设置对象的方法或变量

>>> getattr(s, 'init', None)
<bound method SPAMFilter.init of <__main__.SPAMFilter object at 0x03BF3FF0>>
>>> setattr(s, 'name', 'zhang')
>>> s.name
'zhang'

查看对象内所有的变量

>>> s.__dict__
{'name': 'zhang'}

检查方法是否可以调用

Python2.7

callcble 函数

>>> callable(getattr(s, 'init', None))
True
>>> callable(getattr(s, 'init2', None))
False

Python3

表达式 hasattr(func, "__call__")

>>> hasattr(x, "__call__")
False
>>> hasattr(y, "__call__")
True

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:《Python基础教程》读书笔记07-更加抽象

文章字数:982

本文作者:Bin

发布时间:2017-01-01, 22:34:51

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2017/01/01/Python%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/%E3%80%8APython%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B007-%E6%9B%B4%E5%8A%A0%E6%8A%BD%E8%B1%A1/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录