Python学习_class类笔记 & 异常处理
类的介绍1:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo: # 构造方法, 创建对象的时候会自动执行init构造方法 def __init__(self, bk): self.name = "alex" self.sex = bk print(self.name, self.sex) # 析构方法, 销毁对象的时候自动调用del析构方法 def __del__(self): pass obj1 = Foo("xx") obj2 = Foo("oo")
类的继承:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Animals: xxoo = "test" def chi(self): print(self.name + " 吃") def he(self): print(self.name + " 喝") def piao(self): print(self.name + " Animal piao") class Uncle: def __init__(self, name): print("uncle") self.name = name def piao(self): print(self.name + " Uncle piao") # 可以继承多个类 # 如果都有同一个方法, 优先继承左边的 # 以下规则前提 : 没有共同的基类, 如果有共同基类, 最后找基类 # 【如果没有同一个方法, 则从左到右边开始找, 一直到基类为止, 如果基类没有, 则从第二个开始继续】 class Dog(Animals, Uncle): def __init__(self, name): print("dog") self.name = name print(self.xxoo) def jiao(self): print(self.name + " 汪") # def piao(self): # print(self.name + " piao") alex = Dog("郭磊") # alex.jiao() # alex.chi() # alex.piao()
#!/usr/bin/env python # -*- coding:utf-8 -*- # 继承的补充,方法内继续执行方法时的继承关系 # class A: # def bar(self): # print("Bar") # self.f1() # # def f1(self): # print("A") # # # class B(A): # def f1(self): # print("B") # # # class C: # def f1(self): # print("C") # # # class D(C, B): # pass # # # d1 = D() # d1.bar() # super的用法 class Animal: def __init__(self): print("A的构造方法") self.ty = "动物" class People: def __init__(self): print("P的构造方法") self.sy = "人" class Cat(People, Animal): def __init__(self): print("B的构造方法") self.n = "猫" # self.ty = "动物" # 执行父类的构造方法 [找到Cat类的父类去执行构造方法] super(Cat, self).__init__() # Animal.__init__(self) # 另外一种方式,推荐使用super方法 # 类后面加括号自动执行, 数据初始化 # a = Animal() c = Cat() print(c.__dict__) # import socketserver # # r = socketserver.ThreadingTCPServer() # r.serve_forever()
类的字段&方法&特性:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Provice: # 静态字段,类中 country = "China" def __init__(self, name): # 普通字段,对象中 self.name = name # self.country = "中国" # 普通方法,类中 def show(self): print("Show") # 静态方法 @staticmethod def xo(): print("xo") # 类方法 @classmethod def xxoo(cls): print("xxoo", cls) def start(self): temp = "%s sb" % self.name return temp # 特性,@property装饰器就是负责把一个方法变成属性调用的 @property def end(self): temp = "%s sb" % self.name return temp # 使用end.setter后,可以对特性的值进行设置 @end.setter def end(self, value): # print(value) self.name = value obj = Provice("alex") # 获取字段 print(obj.name) # 修改字段 obj.name = "guolei" print(obj.name) # ret1 = obj.start() # 获取特性 ret2 = obj.end # 设置特性 obj.end = "123" print(obj.end) # print(ret1) # print(ret2) # Provice.xo() # Provice.xxoo() # hebei = Provice("河北") # henan = Provice("河南") # 1.自己的成员自己去访问 # 2.除了类中的方法 # 通过类访问的有:静态字段,静态方法,类方法 # 通过对象访问有:普通字段,普通方法 # print(Provice.country) # 面向对象三大特性: 封装、继承、多态 # 面向对象成员: # 字段 静态字段(每个对象都有一份)、普通字段(每个对象都不同的数据) # 方法 静态方法(无需使用对象封装的内容)、类方法、普通方法(需要使用对象中的数据) # 特性 普通特性(将方法伪造成字段) # obj = Foo("alex") # 反射(以字符串的形式去对象中操作成员) # 反射:对于对象而言,既可以找对象,也可以找类的成员,对于类而言,只能在类里面找 # r = hasattr(Provice, "show") # print(r) # r = hasattr(obj, "name") # print(getattr(obj,"name"))
类的私有字段:
#!/usr/bin/env python # -*- coding:utf-8 -*- # 成员修饰符 : 公有和私有,私有只有自己可以访问 class Foo: xo = "xo" # __表示私有字段,子类里面无法访问 __ox = "ox" def __init__(self): # __表示私有字段,子类里面无法访问 self.__name = "guolei" pass @staticmethod def __fetch(): print(Foo.__ox) @staticmethod def getfetch(): Foo.__fetch() def getadd(self): self.__add() Foo.__fetch(self) # __表示私有类,子类里面无法访问 def __add(self): print(self.__name) obj = Foo() # obj.getadd() Foo.getfetch() # print(obj._Foo__name) # 不常用 # class Bar(Foo): # def fetch(self): # print(self.__name) # print(Foo.xo) # print(Foo.__ox) # obj = Foo() # obj.fetch() # obj = Bar() # obj.fetch() # m = __import__("demo5", fromlist=True) # print(m) # # if hasattr(m, "Provice"): # print("yes") # class_name = getattr(m, "Provice") # obj = class_name("alex") # print(obj) # if hasattr(obj, "name"): # print(getattr(obj, "name")) # else: # print("no")
类的自动执行方法:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __iter__(self): print("iter") yield 1 yield 2 yield 3 # obj = Foo() # li = [] # 如果执行for对象时,自动会执行对象的iter方法,生成器 # for item in obj: # print(item) class Foo: """ 我是类的注释 """ xxxxxxxx = "ooooooooooooo" def __init__(self): self.name = "guolei" print("init") def __call__(self, *args, **kwargs): print("call") return 1 def __getitem__(self, item): print(item, type(item), "__getitem__") def __setitem__(self, key, value): print(key, type(key), value) def __delitem__(self, key): print(key, type(key)) def __str__(self): return "__str__" # r = Foo() # 自动执行__init__方法 # print(r) # 自动执行__str__方法 # print(r.__dict__) # print(Foo.__dict__) # r() # 自动执行__call__方法 # r["k1"] # 自动执行__getitem__方法 # r["k2"] = 123 # 自动执行__setitem__方法 # del r["xxx"] # 自动执行__delitem__方法 # r = list([11, 22, 33, 44, 55, 66, 77]) # print(r[1:5:2]) # 3.7自动执行__getitem__方法 2.7自动执行__getslice__方法 # print(r[1:3]) # 3.7自动执行__setitem__方法 2.7自动执行__setslice__方法 # r[1:3] = [11, 22] # 3.7自动执行__delitem__方法 2.7自动执行__delslice__方法 # del r[1:3] # dic = dict(k1=123, k2=456) # print(dic["k1"]) # dic["k1"] = 111 # del dic["k2"] # print(dic)
异常处理:
#!/usr/bin/env python # -*- coding:utf-8 -*- # 异常处理 # try: # # inp = input("请输入内容:") # # num = int(inp) # # print(num) # li = [] # li[999] # except IndexError as e: # print("索引错误", e, type(e)) # except Exception as e: # print("数据类型转换失败", e, type(e)) # 完整的异常处理模块 try: # 主代码块 pass except KeyError as e: # 异常时,执行该块 pass except IndexError as e: # 异常时,执行该块 pass # else 与 except 只能执行一个 else: # 主代码块执行完,执行该块 pass finally: # 无论异常与否,最终执行该块 pass # raise主动触发异常 # try: # raise KeyError("出错了...") # except Exception as e: # print(e, type(e), e.__dict__) # 断言 assert 1 == 2