1 类的属性,继承,多继承
2 @property @x.setter @x.getter slots @staticmethod @classmethod
3 装饰器 迭代器 生成器
4 内置异常 try except finally raise
1 初识面向对象
封装,继承,多态
2 类的特性
2.1 类的属性和方法
help(cls)
dir(cls) type(cls) id(cls) str(cls)
cls.__dict__
初始化函数__init__(self): 析构函数__del__(self):
__doc__,__module__, __class__, __bases__
2.2 类的实现,实例和判定
class Cat:
def __init__(self):
pass
def show(self):
print("I am a cat")
if __name__ == "__main__":
cat = Cat()
cat.show()
print(isinstance(cat, Cat))
2.3 类的继承和多继承
# 调用父类方法, Tiger为当前类
super(Tiger, self).eat()
issubclass(DuanCat, BaseCat)
class Panda(BaseCat, ProtectedInterface)
issubclass(Panda, BaseCat)
issubclass(Panda, ProtectedInterface)
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
多继承初始化方案
class A:
def __init__(self):
self.a = "A"
print("I am A")
def eat(self):
print("I am eat A")
class B:
def __init__(self):
self.b = "B"
print("I am B")
def beat(self):
print("I am eating b")
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
self.c = "C"
print("I am C")
if __name__ == "__main__":
c = C()
c.eat()
print(c.__dict__)
help(C)
2.4 多态
python基础就支持多态
2.5 类的高级特性 property
property将类的方法当属性使用
class A:
def __init__(self):
self.__age = 100
@property
def show_info(self):
return self.__age
if __name__ == "__main__":
a =A()
print(c.show_info)
@property, @x.getter, @x.setter
https://www.python-course.eu/python3_properties.php
2.6 类的高级特性 slots
1 为指定的类设置一个静态属性空间
2 为属性很少的类节约内存空间
https://stackoverflow.com/questions/472000/usage-of-slots
class A:
__slot__ = ('a',)
class B(A):
__slot__ = ('b', 'c')
2.7 类的事例方法和静态方法
class A:
def __init__(self, name):
self.name = name
print("Create A")
@staticmethod
def breath():
print("I am A")
@classmethod
def show_info(cls, name):
return cls(name)
def show_info2(self):
print(self.name)
if __name__ == "__main__":
c = A.show_info("A")
c.show_info2()
3 面向对象的应用和异常处理
3.1 装饰器
简单装饰器
def log(func):
def wrapper():
print("start")
func()
print("stop")
return wrapper
@log
def func():
print("do something")
带参数的装饰器
def log(name=None):
def decorator(func):
def wrapper(*args, **kwargs)
print("start")
print(func(*args, **kwargs))
return wrapper
def return decorator
@log('hello')
def hello():
print("hello world")
@log('add')
def add(a, b, *args, **kwargs):
return a + b
带参数的装饰器 带上__doc__和__name__等其他属性
def log(name=None):
@wraps(func)
def decorator(func):
def wrapper(*args, **kwargs)
print("start")
print(func(*args, **kwargs))
return wrapper
def return decorator
类装饰器
def f(self):
print("hhh")
print(self.name)
def eat(cls):
#cls.eat = lambda self: print(self.name)
cls.eat = f
@eat
class A:
def __init__(self):
self.name = "A"
if __name__ == '__main__':
a = A()
a.eat()
3.2 迭代器
实现了iter可以用for i in iterable: 比如list(iterable)
实现了next可以用next(a) 或者 a.next()
class PowNumber:
value = 0
def __next__(self):
self.value += 1
if self.value > 10:
raise StopIteration
return self.value ** 2
def __iter__(self):
return self
if __name__ == "__main__":
pow = PowNumber()
print(pow.__next__())
print(next(pow))
for i in pow:
print(i)
3.3 生成器
使用普通函数语法定义的迭代器,函数从yield处冻结返回,下次再从冻结处后面继续执行
def pow():
yield 1
yield 2
def pow2():
return (x ** 2 for x in [1, 2, 3, 4])
def pow3():
for x in [1, 2, 3, 4]:
yield x
if __name__ == "__main__":
for i in pow():
print(i)
for i in pow2():
print(i)
for i in pow3():
print(i)
3.4 异常处理
内置异常
Exception AttributeException OSError IndexError KeyError NameError SyntaxError TypeError ValueError ZeroDivisionError
异常的捕获
def do():
pass
if __name == '__main__':
try:
do()
except (ZeroDivisionError, ValueError) as e:
print(e)
except Exception as e:
pass
finally:
pass
自定义异常
class InvalidCtrlExeption(Exception):
err_code = '1234'
err_msg = 'get wrong'
def __str__(self):
print(self.err_msg)
def do():
try:
raise InvalidCtrlException()
except InvalidCtrlException as e:
print(e)
if __name__ == '__main__':
do()
异常的传递
class MyException(Exception):
pass
def s1():
raise MyException()
def s2():
try:
s1()
print("do")
except MyException as e:
raise e
finally:
print("s2f")
def s3():
try:
s2()
except MyException as e:
print("processed")
finally:
print('s3')
if __name__ == "__main__":
s3()
网友评论