面向对象遗忘补充

概念:

只要存在继承关系,从子类进入到父类中,父类内部方法执行过程中的self就都是子类的实例对象。

如果没有继承关系存在,那其内部方法的self就是该类本身的实例对象。

类/对象的绑定方法,在执行时都会自默认将这个对象或者类以隐藏self的形式传入。

代码:

--

继承理解:

 1 class Fly():
 2     def fly(self):
 3         print('%s会飞' % self.name)
 4 
 5 
 6 class Run():
 7     def run(self):
 8         print('%s会跑' % self.name)
 9 
10 
11 class Eat():
12     def eat(self):
13         print('%s会吃饭' % self.name)
14 
15 
16 class Person(Run, Eat):
17     def __init__(self, name):
18         self.name = name
19 
20 
21 class Bird(Fly, Eat):
22     def __init__(self, name):
23         self.name = name
24 
25 
26 per = Person('chuck')
27 per.eat()
28 per.run()
29 
30 bird = Bird('jinrui')
31 bird.eat()
32 bird.fly()
33 
34 chuck会吃饭
35 chuck会跑
36 jinrui会吃饭
37 jinrui会飞
View Code

 自定义控制文件读写类:

# 定义一个类,控制文件读写,并且在关闭文件时回收cpu资源
class Read():
    def __init__(self,file,io,encoding):
        self.file = file
        self.io = io
        self.encoding = encoding
        self.open_file = open(self.file,self.io,encoding=self.encoding)
    # __del__在调用del时自动调用
    def __del__(self):
        self.open_file.close()
        print('文件关闭')

read= Read(r'C:\Users\Chuck\Desktop\luffy_b\课堂笔记.txt','rt','utf-8')
print(read)
del read
自定义控制文件读写类

 

posted @ 2019-02-23 23:20  ChuckXue  阅读(112)  评论(0编辑  收藏  举报