python面向对象01

如图的继承关系,然后验证经典类与新式类在查找一个属性时的搜索顺序

class B:
	# def test(self):
	# 	print("from B")
	pass
class C:
	# def test(self):
	# 	print("from C")
	pass
class D(B,C):
	# def test(self):
	# 	print("from D")
	pass
class E(B,C):
	def test(self):
		print("from E")
	pass
class F(D,E):
	# def test(self):
	# 	print("from F")
	pass
f = F()
f.test()
# new class (广度优先)
''' F==>D==>E==>B==>C '''
# classical class (深度优先)
''' F==>D==>B==>C==>E '''
基于多态的概念来实现linux中一切皆问题的概念:文本文件,进程,磁盘都是文件,然后验证多态性
class file(object):
	def __init__(self,contents):
		self.contents = contents
	def cat(self):
		print("contents:%s"%(self.contents))
class process(file):
	file_type = 'pid'
	def cat(self):
		print("file_type : %s" %self.file_type)
		#三种方法 调用父类对象,1.super附带当前类名、self代表父类 2.super不附带任何参数 3.父类.方法(self)
		super(process, self).cat()
		#super().cat()
		# file.cat(self)
class disk(file):
	file_type = 'disk'
	def cat(self):
		print("file_type : %s" %self.file_type)
		#三种方法 调用父类对象,1.super附带当前类名、self代表父类 2.super不附带任何参数 3.父类.方法(self)
		super(disk, self).cat()
		#super().cat()
		# file.cat(self)
        
def cat_file(obj):
	''' 调用函数绑定方法 '''
    obj.cat()

proc1 = process("some things")
disk1 = disk("disgusting things")

cat_file(proc1)
cat_file(disk1)
定义老师类,把老师的属性:薪资,隐藏起来,然后针对该属性开放访问接口
苑昊老师有多种癖好,把这种癖好隐藏起来,然后对外提供访问接口
而且以后还会苑昊老师培养很多其他的癖好,对外开放修改接口,可以新增癖好,并且需要保证新增的癖好都是字符串类型,否则无法增加成功。
class Teacher(object):
	__salary = 100
	__hobby = ["kiss egon's ass","和EGON睡觉"]
	def __init__(self,name,age,):
		self.name,self.age = name,age
	def get_salary(self):
		return self.__salary
	def get_hobby(self):
		for x in self.__hobby:
			yield x
	def add_hobby(self,new_hobby):
		if type(new_hobby) == str:
			self.__hobby.append(new_hobby)			
		else:
			print("error!")
t = Teacher("苑昊", 16)
print(t.get_salary())
print("[",t.name,"]","hobby list
-----")
for x in t.get_hobby():
	print(x)
print("-----")
t.add_hobby("女装")
print(t.get_salary())
print("[",t.name,"]","hobby list
-----")
for x in t.get_hobby():
	print(x)
print("-----")
原文地址:https://www.cnblogs.com/anyanyaaaa/p/6740560.html