今日內容
- 嵌套
- 特殊方法:
__init__ - type/isinstance/issubclass/super
- 例外處理
內容回顧
def login():
pass
login()
class Account:
def login(self):
pass
obj = Acount()
obj.login()
-
談談你了解的面向物件?
-
類和物件是什么關系?物件是類的一個實體,
class Foo: def __init__(self,name): self.name = name def run(self): pass obj1 = Foo('ale') obj2 = Foo('eric') -
self是什么?
# self就是一個形式引數,物件呼叫方法時,python內部會將該物件傳給這個引數, class Foo: def run(self,num): pass obj = Foo() obj.run(5) -
類成員 & 物件成員 以及他們之間的關系,
class Foo: name = 'alex' def run(self): pass obj = Foo() -
類/方法/物件 都可以當作變數或嵌套到其他型別中,
class Foo: def run(self): pass v = [Foo,Foo] v = [Foo(),Foo()] obj = Foo() v = [obj.run,obj.run,obj.run]class School(object): def __init__(self,title): self.title = title class Course(object): def __init__(self,name,school_object): self.name = name self.school = school_object class Classes(object): def __init__(self,cname,course_object): self.cname = cname self.course = course_object s1 = School('北京') c1 = Course('Python',s1) c2 = Course('Go',s1) cl1 = Classes('全堆疊1期',c1)class School(object): def __init__(self,title): self.title = title def rename(self): pass class Course(object): def __init__(self,name,school_object): self.name = name self.school = school_object def reset_price(self): pass class Classes(object): def __init__(self,cname,course_object): self.cname = cname self.course = course_object def sk(self): pass s1 = School('北京') c1 = Course('Python',s1) c2 = Course('Go',s1) cl1 = Classes('全堆疊1期',c1)
內容詳細
1.嵌套
- 函式:引數可以是任意型別,
- 字典:物件和類都可以做字典的key和value
- 繼承的查找關系
class StarkConfig(object):
pass
class AdminSite(object):
def __init__(self):
self.data_list = []
def register(self,arg):
self.data_list.append(arg)
site = AdminSite()
obj = StarkConfig()
site.register(obj)
class StarkConfig(object):
def __init__(self,name,age):
self.name = name
self.age = age
class AdminSite(object):
def __init__(self):
self.data_list = []
self.sk = None
def set_sk(self,arg):
self.sk = arg
site = AdminSite() # data_list = []
site.set_sk(StarkConfig)
sk = StarkConfig
site.sk('alex',19)
class StackConfig(object):
pass
class Foo(object):
pass
class Base(object):
pass
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg):
self._register[key] = arg
site = AdminSite()
site.registry(1,StackConfig)
site.registry(2,StackConfig)
site.registry(3,StackConfig)
site.registry(4,Foo)
site.registry(5,Base)
for k,v in site._register.items():
print(k,v() )
class StackConfig(object):
pass
class UserConfig(StackConfig):
pass
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg=StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
print(key,obj)
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
class StackConfig(object):
list_display = '李邵奇'
class UserConfig(StackConfig):
list_display = '利奇航'
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg=StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
print(key,obj.list_display)
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
class StackConfig(object):
list_display = '李邵奇'
def changelist_view(self):
print(self.list_display)
class UserConfig(StackConfig):
list_display = '利奇航'
class AdminSite(object):
def __init__(self):
self._register = {}
def registry(self,key,arg=StackConfig):
self._register[key] = arg
def run(self):
for key,value in self._register.items():
obj = value()
obj.changelist_view()
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()
2.特殊成員
2.1 __init__
class Foo:
"""
類是干啥的,,,,
"""
def __init__(self,a1):
"""
初始化方法
:param a1:
"""
self.a1 = a1
obj = Foo('alex')
2.2 __new__
class Foo(object):
def __init__(self):
"""
用于給物件中賦值,初始化方法
"""
self.x = 123
def __new__(cls, *args, **kwargs):
"""
用于創建空物件,構造方法
:param args:
:param kwargs:
:return:
"""
return object.__new__(cls)
obj = Foo()
2.3 __cal__
class Foo(object):
def __call__(self, *args, **kwargs):
print('執行call方法')
# obj = Foo()
# obj()#物件后面加括號,執行的是類中的__call__方法,
Foo()()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from wsgiref.simple_server import make_server
def func(environ,start_response):
start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')])
return ['你好'.encode("utf-8") ]
class Foo(object):
def __call__(self, environ,start_response):
start_response("200 OK", [('Content-Type', 'text/html; charset=utf-8')])
return ['你<h1 style="color:red;">不好</h1>'.encode("utf-8")]
# 作用:寫一個網站,用戶只要來方法,就自動找到第三個引數并執行,
server = make_server('127.0.0.1', 8000, Foo())
server.serve_forever()
2.4 __getitem__ __setitem__ __delitem__
class Foo(object):
def __setitem__(self, key, value):
pass
def __getitem__(self, item):
return item + 'uuu'
def __delitem__(self, key):
pass
obj1 = Foo()
obj1['k1'] = 123 # 內部會自動呼叫 __setitem__方法
val = obj1['xxx'] # 內部會自動呼叫 __getitem__方法
print(val)
del obj1['ttt'] # 內部會自動呼叫 __delitem__ 方法
2.5 __str__
class Foo(object):
def __str__(self):
"""
只有在列印物件時,會自動化呼叫此方法,并將其回傳值在頁面顯示出來
:return:
"""
return 'asdfasudfasdfsad'
obj = Foo()
print(obj)
class User(object):
def __init__(self,name,email):
self.name = name
self.email = email
def __str__(self):
return "%s %s" %(self.name,self.email,)
user_list = [User('二狗','[email protected]'),User('二蛋','[email protected]'),User('狗蛋','[email protected]')]
for item in user_list:
print(item)
2.6 __dict__
class Foo(object):
def __init__(self,name,age,email):
self.name = name
self.age = age
self.email = email
obj = Foo('alex',19,'[email protected]')
print(obj)
print(obj.name)
print(obj.age)
print(obj.email)
val = obj.__dict__ # 去物件中找到所有變數并將其轉換為字典
print(val)
2.7 背景關系管理【面試題】
class Foo(object):
def __enter__(self):
self.x = open('a.txt',mode='a',encoding='utf-8')
return self.x
def __exit__(self, exc_type, exc_val, exc_tb):
self.x.close()
with Foo() as ff:
ff.write('alex')
ff.write('alex')
ff.write('alex')
ff.write('alex')
# class Context:
# def __enter__(self):
# print('進入')
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# print('推出')
#
# def do_something(self):
# print('內部執行')
#
# with Context() as ctx:
# print('內部執行')
# ctx.do_something()
class Foo(object):
def do_something(self):
print('內部執行')
class Context:
def __enter__(self):
print('進入')
return Foo()
def __exit__(self, exc_type, exc_val, exc_tb):
print('推出')
with Context() as ctx:
print('內部執行')
ctx.do_something()
2.8 兩個物件相加
val = 5 + 8
print(val)
val = "alex" + "sb"
print(val)
class Foo(object):
def __add__(self, other):
return 123
obj1 = Foo()
obj2 = Foo()
val = obj1 + obj2
print(val)
特殊成員:就是為了能夠快速實作執行某些方法而生,
3.內置函式補充
3.1 type,查看型別
class Foo:
pass
obj = Foo()
if type(obj) == Foo:
print('obj是Foo類的物件')
3.2 issubclass
class Base:
pass
class Base1(Base):
pass
class Foo(Base1):
pass
class Bar:
pass
print(issubclass(Bar,Base))
print(issubclass(Foo,Base))
3.3 isinstance
class Base(object):
pass
class Foo(Base):
pass
obj = Foo()
print(isinstance(obj,Foo)) # 判斷obj是否是Foo類或其基類的實體(物件)
print(isinstance(obj,Base)) # 判斷obj是否是Foo類或其基類的實體(物件)
4.super
class Base(object):
def func(self):
print('base.func')
return 123
class Foo(Base):
def func(self):
v1 = super().func()
print('foo.func',v1)
obj = Foo()
obj.func()
# super().func() 去父類中找func方法并執行
class Bar(object):
def func(self):
print('bar.func')
return 123
class Base(Bar):
pass
class Foo(Base):
def func(self):
v1 = super().func()
print('foo.func',v1)
obj = Foo()
obj.func()
# super().func() 根據類的繼承關系,按照順序挨個找func方法并執行(找到第一個就不在找了)
class Base(object): # Base -> object
def func(self):
super().func()
print('base.func')
class Bar(object):
def func(self):
print('bar.func')
class Foo(Base,Bar): # Foo -> Base -> Bar
pass
obj = Foo()
obj.func()
# super().func() 根據self物件所屬類的繼承關系,按照順序挨個找func方法并執行(找到第一個就不在找了)
5.例外處理
5.1 基本格式
try:
pass
except Exception as e:
pass
try:
v = []
v[11111] # IndexError
except ValueError as e:
pass
except IndexError as e:
pass
except Exception as e:
print(e) # e是Exception類的物件,中有一個錯誤資訊,
try:
int('asdf')
except Exception as e:
print(e) # e是Exception類的物件,中有一個錯誤資訊,
finally:
print('最后無論對錯都會執行')
# #################### 特殊情況 #########################
def func():
try:
# v = 1
# return 123
int('asdf')
except Exception as e:
print(e) # e是Exception類的物件,中有一個錯誤資訊,
return 123
finally:
print('最后')
func()
5.2 主動觸發例外
try:
int('123')
raise Exception('阿薩大大是阿斯蒂') # 代碼中主動拋出例外
except Exception as e:
print(e)
def func():
result = True
try:
with open('x.log',mode='r',encoding='utf-8') as f:
data = https://www.cnblogs.com/cuiyongchao007/p/f.read()
if'alex' not in data:
raise Exception()
except Exception as e:
result = False
return result
5.3 自定義例外
class MyException(Exception):
pass
try:
raise MyException('asdf')
except MyException as e:
print(e)
class MyException(Exception):
def __init__(self,message):
super().__init__()
self.message = message
try:
raise MyException('asdf')
except MyException as e:
print(e.message)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/193114.html
標籤:Python
上一篇:關于malloc與free的問題
下一篇:python基礎資料型別整理
