面向对象学习笔记(3)

part3

1.嵌套

  • 函数:参数可以是任意类型。

  • 字典:对象和类都可以做字典的key和value。

    class Foo(object):
        pass
    
    obj1 = Foo()
    obj2 = Foo()
    
    info = {"1":1,Foo:2,obj1:3,obj2:4}
    print(info)
    print(info[Foo])
    
  • 继承的查找关系

    class StartConfig:
        pass
    
    class AdminSite:
        def __init__(self):
            self.data_list = []
            
        def register(self,arg):
            self.data_list.append(arg)
    
    site = AdminSite()
    obj = StartConfig()
    site.register(obj)
    
    class StartConfig:
        def __init__(self,age,name):
            self.name = name
            self.age = age
    
    
    class AdminSite:
        def __init__(self):
            self.data_list = []
            self.sk = None
    
        def set_sk(self,arg):
            self.sk = arg
    
    site = AdminSite()
    site.set_sk(StartConfig)
    site.sk("a1",10)
    
    class Foo1:
        pass
    
    class Foo2(Foo1):
        pass
    
    class AdminSite:
        def __init__(self):
            self._register = {}
        def register(self,key,value = Foo1):
            self._register[key] = value
    
        def run(self):
            for item in self._register.values():
                obj = item()
                print(obj)
    
    site = AdminSite()
    site.register(1)
    site.register(2,Foo1)
    site.register(3,Foo2)
    site.run()
    
    class Foo1:
        list_display = 'Foo1'
    
    class Foo2(Foo1):
        list_display = "Foo2"
    
    class AdminSite:
        def __init__(self):
            self._register = {}
        def register(self,key,value = Foo1):
            self._register[key] = value
    
        def run(self):
            for key,value in self._register.items():
                obj = value()
                print(key,obj.list_display)
    
    site = AdminSite()
    site.register(1)
    site.register(2,Foo1)
    site.register(3,Foo2)
    site.run()
    
    class Foo1:
        list_display = 'Foo1'
    
        def func1(self):
            print("foo1_func1")
    
    class Foo2(Foo1):
        list_display = "Foo2"
    
    class AdminSite:
        def __init__(self):
            self._register = {}
        def register(self,key,value = Foo1):
            self._register[key] = value
    
        def run(self):
            for key,value in self._register.items():
                obj = value()
                obj.func1()
    
    site = AdminSite()
    site.register(1)
    site.register(2,Foo1)
    site.register(3,Foo2)
    site.run()
    

2.特殊成员(*)

为了能够快速实现执行某些方法而生。

1.__init__
class Foo:
    '''
    类注释
    '''
    def __init__(self,name):
        '''
        初始化方法
        '''
        self.name = name
# 1.创建一个空对象 obj
# 2.执行 __init__ ,给对象中进行赋值初始化
obj = Foo("a1")
2.__new__
class Foo:
    def __init__(self):
        '''
        用于给对象中赋值,初始化方法
        '''
        print('init')
        self.x = 123
    def __new__(cls, *args, **kwargs):
        '''
        用于创建空对象,构造方法
        :param args:
        :param kwargs:
        '''
        print("new")
        return object.__new__(cls) # 相当于这个方法没写(默认继承object)
obj = Foo()
3.__call__
class Foo:
    def __call__(self, *args, **kwargs):
        print("执行call方法")
obj = Foo()
obj() # 对象后面加()   python独有的
Foo()()
# 如果没有call方法,直接对象()是会报错的!
from wsgiref.simple_server import make_server

def func(environ,start_response):
    start_response("200 OK",[("Content-Type","text/plain;charset=gbk")])
    return ["你好".encode("gbk")]

class Foo:
    def __call__(self, environ,start_response):
        start_response("200 OK", [("Content-Type", "text/plain;charset=gbk")])
        return ['你不好'.encode("gbk")]
    
# 作用:写一个网站,用户只要来访问,就自动找到第三个参数并执行
server = make_server('127.0.0.1',8000,Foo())
# server = make_server('127.0.0.1',7000,func()) # 效果同上
server.serve_forever()
4.__getitem__ __setitem__ __delitem__
obj = dict()
obj['k1'] = 123
del obj['k1']
# 正常运行

class Foo:
    pass

obj1 = Foo()
obj1['k1'] = 123
# 报错

class Foo:
    def __setitem__(self, key, value):
        print(key,value)

obj1 = Foo()
obj1['k1'] = 123 # 内部自动调用__setitem__方法
# 不会报错
# 结果为: k1 123
class Foo:
    def __setitem__(self, key, value):
        print(key,value)

obj1 = Foo()
obj1['k1'] # 取值 => 报错

class Foo:
    def __setitem__(self, key, value):
        print(key,value)
    def __getitem__(self, item):
        return item+"uuu"

obj1 = Foo()
a = obj1['k1'] # 内部自动调用__getitem__方法
print(a)
class Foo:
    def __setitem__(self, key, value):
        print(key,value)
    def __getitem__(self, item):
        return item+"uuu"
    
obj1 = Foo()
obj1['k1'] = 123
del obj1['k1'] # 报错

class Foo:
    def __setitem__(self, key, value):
        print(key,value)
    def __getitem__(self, item):
        return item+"uuu"
    def __delitem__(self, key):
        pass
obj1 = Foo()
obj1['k1'] = 123
del obj1['k1'] # 内部自动调用__delitem__方法

5.__str__
str1 = "sad"
print(str1) # 这是字符串

class Foo:
    def __str__(self):
        """
        只有在打印对象时,会自动化调用此方法,并将其返回值在页面显示出来。
        :return: 
        """
        return "sad"
obj = Foo()
print(obj) # 这是对象
6.__dict__
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age

obj = Foo("a1",10)
print(obj)
print(obj.name)
print(obj.age)
val = obj.__dict__ # 去对象中找到所有变量并将其转换为字典
print(val)
7.__enter__ __exit__
class Foo:
    # 如果要使用with+实例化对象,则必须要使用下面两个类方法
    # 先__enter__,然后执行with的内容,最后执行__exit__
    def __enter__(self):
        print("enter")
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")

# obj = Foo()
# with obj:  # 同下
with Foo():
    print(123)

上下文管理【面试题】

class Foo:
    def __enter__(self):
        self.x = open("text2_1.txt",mode="a",encoding="utf-8")
        return self.x
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.x.close()

with Foo() as f:
    f.write("text2")
    f.write("嘻嘻嘻")
8.__add__
class Foo:
    def __add__(self, other):
        return 123

obj1 = Foo()
obj2 = Foo()
cal = obj1 + obj2 # 此时执行的是obj1里的__add__
print(cal)

3.内置函数

1.type
# 查看类型
class Foo:
    pass
obj = Foo()
if type(obj) == Foo:
    print("obj是Foo类的对象")
2.issubclass
# 判断是否是子类
class Base:
    pass

class Base1(Base):
    pass

class Base2(Base1):
    pass

class Foo:
    pass
print(issubclass(Base1,Base)) # True
print(issubclass(Base2,Base)) # True
print(issubclass(Foo,Base)) # # False
3.isinstance
# 判断是否是某类或其基类的实例(与tyoe区分)
class Base1(object):
    pass

class Base2(object):
    pass

obj = Base1()
print(isinstance(obj,Base1)) # True
print(isinstance(obj,Base2)) # False

# 与type区分
class Base1(object):
    pass

class Base2(Base1):
    pass

obj = Base2()
print(isinstance(obj,Base1)) # True
print(isinstance(obj,Base2)) # True
print(type(obj)) # Base2
# 绝对判断用type

4.super

class Base:
    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()
class Bar:
    def func(self):
        print("Base.func")
        return 123

class Base(Bar):
    pass

class Foo(Base):
    def func(self):
        v1 = super().func() 根据类的继承关系
        print("Foo.func",v1)

obj = Foo()
obj.func() 
class Base:
    def func(self):
        super().func()
        print("base.func")

class Bar:
    def func(self):
        print("Bar.func")

class Foo(Base,Bar):
    pass

obj = Foo()
obj.func()
# 查找顺序实例化对象的所有基类: Foo => Base => Bar 
# (过程中遇到的所有super都会按照这个顺序继续寻找直至执行)

# obj = Base()
# obj.func()
# 报错

5.异常处理

基本格式
try:
    pass
except Exception as e:
    pass
# int("sdas")
# ValueError: invalid literal for int() with base 10: 'sdas'
# v = []
# v[10]
# IndexError: list index out of range
try:
    int("sdas")
    # v = []
    # v[10]
except ValueError as e:
    print(e)
except IndexError as e:
    print(e)
except Exception as e: # e是Exception类的一个对象,其中有个错误信息
    print(e)
# invalid literal for int() with base 10: 'sdas'
finally:
    print("无论对错都会执行")
# 特殊情况
def func():
    try:
        v = 1
        return "ok"
    except Exception as e:
        print(e)
    finally:
        print("无论对错都会执行")

v1 = func()
print(v1) # 结果无论异常与否都会执行finally
#结果: 无论对错都会执行
#      ok
主动触发异常
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 = f.read()
        # 此时会报错因为x.log不存在
        if "alex" not in data:
            raise Exception()
        # 如果读到对应文件但是没找到"alex"也会报错
    except Exception as e:
        result = False # 针对上述问题统一处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值