反射
class Black:
ture = 'Ugly'
def __init__(self, name, addr):
self.name = name
self.addr = addr
# def sell_house(self):
# return_value = '%s 正在卖房子' % self.name
# return return_value
def rent_house(self):
return_value = '%s 正在租房子' % self.name
return return_value
c1 = Black('alex', '北京')
if hasattr(c1, 'sell_house'): # 判断c1后的的方法,如果有返回True
func = getattr(c1, 'sell_house')
print(func())
else:
print('没有此方法')
pass
多态
# 多态
class H2o:
def __init__(self, status, c):
self.status = status
self.c = int(c)
def main(self):
if 100 > self.c > 0:
print('水在%s度下是水' % self.c)
if self.c >= 100:
print('水在%s度下是蒸汽' % self.c)
if self.c <= 0:
print('水在%s度下是冰' % self.c)
class Water(H2o):
pass
class Ice(H2o):
pass
class Steam(H2o):
pass
w = Water('水', 50)
i = Ice('冰', -20)
s = Steam('蒸汽', 300)
w.main()
i.main()
s.main()
授权
import time
class Open:
def __init__(self, filename, mode='r', encoding='utf8'):
self.filename = filename
self.mode = mode
self.encoding = encoding
self.file = open(filename, mode, encoding=encoding)
def write(self, line):
t = time.strftime('%Y-%m-%d %X')
self.file.write('%s %s' % (t, line))
def __getattr__(self, item):
return getattr(self.file, item)
open1 = Open('授权/a.txt', 'r+')
open1.write('1\n')
open1.write('2\n')
open1.write('3\n')
# open1.write('4\n')
# open1.seek(0)1
# print(open1.read())
封装
class People:
__stat = 'earth'
def __init__(self, people_id, people_name):
self.id = people_id
self.name = people_name
def get(self):
return_value = '我是%s,ID为:%s,' % (self.name, self.id)
return return_value
p1 = People('001', 'alex')
# print(p1.get())
class S:
def __init__(self, long, wide, high):
self.__long = long
self.__wide = wide
self.__high = high
def s(self):
return self.__long * self.__wide
def long(self):
return self.__long
def wide(self):
return self.__wide
s1 = S(3, 2, 2)
print(s1.s())
作者:Alice只敲代码不秃头