1. 程式人生 > 實用技巧 >Python就業班——初識面向物件

Python就業班——初識面向物件

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:practice
# File:Python就業班——初識面向物件.py
# Data:2020/7/10 16:15
# Author:LGSP_Harold


# 判斷一個物件是否是一個已知的型別
# isinstance(obj, class)
# isinstance(22, int)
# 判斷是否為子類
# issubclass(Cat, BaseCat)  True or False




# ————————————————————————————
# @property:將類的方法當做屬性來使用 # class Cat(object): # # def __init__(self, name, age): # self.name = name # self.__age = age # # @property # def age(self): # return self.__age # # @age.setter # def age(self, value): # if not isinstance(value, int): # print('年齡只能是整數')
# return 0 # if not 0 <= value <= 100: # print('年齡只能介於0-100之間') # return 0 # self.__age = value # # @property # def show_info(self): # return '我叫{0},今年{1}歲'.format(self.name, self.age) # ————————————————————————————
# __slots__:為指定的類設定一個靜態屬性列表,為屬性很少的類節約記憶體空間 # class Cat(object): # __slots__ = ('name', 'age') # # def __init__(self, name, age): # self.name = name # self.age = age # # @property # def show_info(self): # return '{0},{1}'.format(self.name, self.age) # # def __str__(self): # return '我的物件:{0}'.format(self.name) # # # def eat(): # print('我吃魚') # # # class DuanCat(Cat): # """ # 藍短貓 # """ # pass # # # class PersianCat(Cat): # """ # 波斯貓 # """ # __slots__ = ('sex', 'eat', ) # pass # ———————————————————————————— # 類的靜態方法和例項方法 # @staticmethod:表示靜態方法 # @classmethod:類的方法 # class Cat(object): # # tag = '貓科' # # def __init__(self, name): # self.name = name # # @staticmethod # def breath(): # print('呼吸') # # def show_info(self): # print('類的屬性:{0},例項的屬性:{1}'.format(self.tag, self.name)) # # # @classmethod # # def show_info1(cls): # # # cls.name ==> Cat.name # # print('類的屬性:{0},例項的屬性:{1}'.format(cls.tag, cls.name)) # # @classmethod # def show_info2(cls, name): # # cls.name ==> Cat.name # # print('類的屬性:{0},例項的屬性:{1}'.format(cls.tag, cls.name)) # return cls(name) # ———————————————————————————— # 裝飾器 # 用來拓展原來函式功能的一種函式 # 返回函式的函式 # 在不用更改原函式的程式碼前提下給函式增加新的功能 # def log(func): # def wrapper(): # print('start....') # func() # print('end....') # return wrapper # # # @log # def hello(): # print('hello') # 帶引數的裝飾器 # def log(name=None): # def decorator(func): # def wrapper(): # print('{0}Start....'.format(name)) # func() # print('{0}End....'.format(name)) # return wrapper # return decorator # # # @log() # @log('you') # def hello(): # print('hello') # # # def log(name=None): # def decorator(func): # def wrapper(*args, **kwargs): # print('{0}Start....'.format(name)) # print(args) # print(kwargs) # rest = func(*args, **kwargs) # print('{0}End....'.format(name)) # return rest # return wrapper # return decorator # # # @log('from add') # def add(a, b, *args, **kwargs): # return a + b # def log(func): # def wrapper(*args, **kwargs): # rest = func(*args, **kwargs) # return rest # return wrapper # # # @log # def add(*args, **kwargs): # j = 0 # for item in args: # j += item # return j # # @wraps(func)用法 # def log(name=None): # def decorator(func): # @wraps(func) # def wrapper(a, b, *args, **kwargs): # """ 裝飾器內部的函式 """ # print('Start,{0}'.format(name)) # print('{0}{1}'.format(func.__name__,func.__doc__)) # num = func(a, b, *args, **kwargs) # print('End') # return num # print('{0}{1}'.format(func.__name__, func.__doc__)) # return wrapper # return decorator # # # @log('Leslie') # def add(a, b, *args, **kwargs): # """ 加法計算 """ # return a + b # # 類的裝飾器 # def func(self): # print('{0}我要吃東西【func()】'.format(self.name)) # # # def eat(cls): # """ 吃東西裝飾器 """ # cls.eat = lambda self: print('{0}我要吃東西【eat()】'.format(self.name)) # cls.eat1 = func # return cls # # # @eat # class Dog(object): # """ 狗類 """ # def __init__(self, name): # self.name = name # ———————————————————————————— # 迭代器 # 1、迭代(iterate)意味著重複多次,就像迴圈那樣(list,tuple) # 2、實現了方法__iter__的物件是可迭代的,而實現了方法__next__的物件是迭代器 # 3、呼叫方法__next__時,(或next()),迭代器返回其下一個值 # 4、如果迭代器沒有可供返回的值,觸發StopIteration異常 # 從迭代器建立序列 # class PowNumber(object): # """ # 迭代器 # 生成1,2,3,....數的平方 # """ # value = 0 # def __next__(self): # self.value += 1 # if self.value > 20: # raise StopIteration # return self.value * self.value # # def __iter__(self): # return self # ———————————————————————————— # 生成器 # 生成器是一種使用普通函式語法定義的迭代器 # 包含yield語句的函式都被稱為生成器 # 不使用return返回一個值,而是可以生成多個值,每次一個 # 每次使用yield生成一個值後,函式都將凍結,即在此停止執行 # 被重新喚醒後,函式將從停止的的地方開始繼續執行 # def pow(): # yield 1 # yield 2 # yield 3 # yield 4 # yield 5 # yield 6 # # # def pow_number(): # return (x * x for x in [1, 2, 3, 4, 5]) # # # def pow_number1(): # for x in [1, 2, 3, 4, 5]: # yield x * x # 模擬range函式 # # 迭代器 # class IterRange(object): # # def __init__(self, start, end): # self.start = start - 1 # self.end = end # # def __next__(self): # self.start += 1 # if self.start >= self.end: # raise StopIteration # return self.start # # def __iter__(self): # return self # # # # 生成器 # class GenRange(object): # # def __init__(self, start, end): # self.start = start # self.end = end # # def get_num(self): # while True: # if self.start >= self.end: # break # yield self.start # self.start += 1 # # # def imitate_range(start, end): # while True: # if start >= end: # break # yield start # start += 1 # ———————————————————————————— # 異常捕獲 # try: # pass # except Exception as err: # print(err) # finally: # pass # 自定義異常 # class ApiException(Exception): # err_code = '' # err_msg = '' # def __init__(self, err_code=None, err_msg=None): # self.err_code = self.err_code if self.err_code else err_code # self.err_msg = self.err_msg if self.err_msg else err_msg # def __str__(self): # return 'Error{0}-{1}'.format(self.err_code, self.err_msg) # # # class InvalidCtrlExec(ApiException): # err_code = '40001' # err_msg = '不合法呼叫憑證' # # # class BadPramsException(ApiException): # err_code = '40002' # err_msg = '兩個引數必須都是整數' # # # # # def divide(num1, num2): # if not isinstance(num1, int) or not isinstance(num2, int): # raise BadPramsException() # if num2 == 0: # raise ApiException('40000', '除數不能為0') # return num1 / num2 # # 丟擲異常及異常的傳遞 # class MyException(Exception): # pass # # # def v_for(): # """ 自定義函式 """ # for i in range(1, 100): # if i == 20: # raise MyException # print(i) # # # def call_v_for(): # """ 呼叫v_for函式 """ # print("開始呼叫") # v_for() # print("結束呼叫") # # # def test_rasie(): # print("測試函式") # try: # call_v_for() # except MyException: # print('____________________________') # print("測試完畢") if __name__ == '__main__': # cat = Cat('XX', 10) # rest = cat.show_info # print(rest) # cat.age = 10 # rest = cat.show_info # print(rest) # ———————————————————————————— # cat_b = Cat('xx', 12) # rest = cat_b.show_info # print(rest) # # 給例項新增新的屬性 # cat_b.color = 'while' # print(cat_b.color) # # 給例項新增新的方法 # cat_b.eat = eat # cat_b.eat() # 使用slots後不允許給例項新增新的屬性 # cat_b.color = 'black' # print(cat_b.color) # 使用slots後不允許給例項新增新的方法 # cat_b.eat = eat # cat_b.eat() # # 使用__slots__要注意,__slots__定義的屬性僅對當前類起作用,對繼承的子類是不起作用的:(視訊此處總結有誤) # duan_cat = DuanCat('oo', 15) # rest = duan_cat.show_info # print(rest) # duan_cat.color = 'blue' # print(duan_cat.color) # # 在子類中也定義__slots__,這樣,子類允許定義的屬性就是自身的__slots__加上父類的__slots__。 # persian_cat = PersianCat('hh', 0) # rest = persian_cat.show_info # print(rest) # persian_cat.sex = '母' # print(persian_cat.sex) # persian_cat.eat = eat # persian_cat.eat() # persian_cat.color = 'while' # print(persian_cat.color) # ———————————————————————————— # # 通過類進行呼叫 # Cat.breath() # cat = Cat('小黑') # # 通過類的例項化進行呼叫 # cat.breath() # cat.show_info() # # cat.show_info1() # 此處視訊內容不知是太難了還是講師只是講個大概(類方法),反正我沒聽懂,建議看文件自行理解。 # 呼叫classmethod # cat2 = Cat.show_info2('oo') # cat2.show_info() # ———————————————————————————— # hello() # hello() # rest = add(5, 6) # print(rest) # rest = add(5, 6) # print(rest) # rest = add(5, 6) # print('{0}{1}'.format(add.__name__, add.__doc__)) # print(rest) # # 類的裝飾器 # dog = Dog('小黑') # dog.eat() # dog.eat1() # ———————————————————————————— # 迭代器 # pow = PowNumber() # print(pow.__next__()) # print(pow.__next__()) # print(next(pow)) # print(next(pow)) # for i in pow: # print(i) # ———————————————————————————— # 生成器 # rest = pow() # print(next(rest)) # print(next(rest)) # print(next(rest)) # print('__________________') # for i in rest: # print(i) # print('__________________') # rest1 = pow_number1() # print(rest1.__next__()) # print(next(rest1)) # ———————————————————————————— # 模擬range函式 # iter = IterRange(5, 10) # print(list(iter)) # # gen = GenRange(5, 10).get_num() # print(list(gen)) # # imitate = imitate_range(5, 10) # print(list(imitate)) # ———————————————————————————— # 自定義異常 # try: # rest = divide(4, 0) # # rest = divide(4, "00") # print(rest) # # except ApiException as err: # print('出錯了') # print(err) # test_rasie() pass