声明:学习笔记,参考B站视频 https://www.bilibili.com/video/BV1Cq4y1Q7Qv?p=12
鸭子类型和多态
'''
鸭子类型
当看到一只鸟走起来像鸭子
游泳起来像鸭子,叫起来也像鸭子
那么这只鸟就可以被成为鸭子
'''
class Cat(object):
def say(self):
print('i am a cat')
class Dog(object):
def say(self):
print('i am a dog')
class Duck(object):
def say(self):
print('i am a duck')
animal_list = [Cat, Dog, Duck]
for animal in animal_list:
animal().say()
'''
运行结果:
i am a cat
i am a dog
i am a duck
'''
'''
多态:
python中不一定需要非要继承某个类才可以实现某个方法
所有类都实现了一个共同的方法(方法名一样)就可以实现多态
'''
a = [1, 2]
b = [3, 4]
tuple_list = [5, 6]
set_list = set()
set_list.add(7)
set_list.add(8)
a.extend(b)
print(a)
b.extend(tuple_list)
print(b)
tuple_list.extend(set_list)
print(tuple_list)
isinstance和type的区别
class A:
pass
class B(A):
pass
b = B()
print(isinstance(b,B))
print(isinstance(b,A))
print(type(b))
print(type(b) is B)
print(type(b) is A)
类变量和实例变量
class A:
aa = 11
def __init__(self, x, y):
self.x = x
self.y = y
a = A(1, 2)
print(a.x)
print(a.y)
print(a.aa)
print(A.aa)
A.aa = 22
print(a.aa)
a.aa = 100
print(a.aa)
print(A.aa)
b = A(3, 5)
print(b.aa)
实例方法
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return '{}/{}/{}'.format(self.year, self.month, self.day)
def tomorrow(self):
self.day += 1
if __name__ == '__main__':
new_day = Date(2018, 12, 31)
print(new_day)
new_day.tomorrow()
print(new_day)
静态方法 @staticmethod
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return '{}/{}/{}'.format(self.year, self.month, self.day)
@staticmethod
def parse_from_string(date_str):
year, month, day = tuple(date_str.split('-'))
return Date(int(year), int(month), int(day))
@staticmethod
def from_string(date_str):
year, month, day = tuple(date_str.split('-'))
if year > 2000:
return True
else:
return False
if __name__ == '__main__':
'''
不使用静态方法示例(繁琐 每个对象的调用都有重复操作)
'''
date_str = '2018-12-31'
year, month, day = tuple(date_str.split('-'))
new_day = Date(int(year), int(month), int(day))
print(new_day)
'''
使用静态方法(staticmethod)后的示例(直接定义到类内部中)
'''
new_day = Date.parse_from_string('2018-12-31')
print(new_day)
类方法 @classmethod
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return '{}/{}/{}'.format(self.year, self.month, self.day)
@classmethod
def parse_from_string(cls, date_str):
year, month, day = tuple(date_str.split('-'))
return cls(int(year), int(month), int(day))
if __name__ == '__main__':
'''
类方法比静态方法灵活
'''
new_day = Date.parse_from_string('2018-12-31')
print(new_day)
|