zoukankan      html  css  js  c++  java
  • 成员,成员修饰符,特殊方法__call,iter,dict,str,init,异常处理

    class Animal():
    country = "china"#静态字段
    __country = "ch"#加双下划线修饰,只能内部方法调用
    def __init__(self):
    print("animal")
    def __call__(self, *args, **kwargs):
    print("call")
    # obj3 = Animal()类后加括号执行init,对象后加括号执行call
    # obj3()
    # Animal()()
    def __getitem__(self, item):#对象后[],执行
    print(item)
    #obj4 = Animal()
    #obj4["asdasd"]
    def __setitem__(self, key, value):#obj4["xxx"] = 123
    pass
    def __delitem__(self, key):#del obj4["xxx"]
    pass
    def __country(self):#成员修饰符__,只能内部访问,
    # (默认只能,非要访问,obj._Animal__country)
    pass
    class Dog(Animal):

    def __init__(self,name):
    self.name = name
    print("dog")
    super(Dog,self).__init__()#执行父类的构造方法
    #Animal.__init__(self)
    @staticmethod
    def xx():#静态方法
    pass
    @classmethod
    def xo(cls):#类方法,至少要一个cls参数(特殊的静态方法)
    pass
    @property#获取
    def xp(self):#特性,将方法伪造成一种字段
    print("xp")
    @xp.setter#设置
    def xp(self,value):
    print(value)
    # obj = Dog()
    # #查找源码的过程(self。xxxx(),从底层开始找)
    # #用反射查找
    # print(hasattr(Dog,"__init__"))#反射类,只能找类里的成员
    # print(hasattr(obj,"__init__"))#反射对象,既可以找对象,又可以找类里的成员

    print(Animal.country)#静态字段通过类去访问,普通字段通过对象去访问
    Dog.xx()#静态方法直接通过类去访问
    Dog.xo()#自动获取当前类名Dog,并通过cls传入
    obj = Dog("tom")
    obj.xp = 123
    # 成员:
    # 字段 静态字段(每个对象都有一份) 普通字段(每个对象都有不同的数据)
    # 方法 静态方法(无需使用对象封装的内容) 类方法 普通方法(使用对象中的数据)
    # 特性 普通特性(将方法伪造成字段)
    # 快速判断,类执行,对象执行:
    # self,对象调用
    # 无self,类调用
    print(obj.__dict__)#获取所有字段
    # 如果执行for对象时,自动会执行对象的__iter__方法,生成器
    l1 = []
    inp = input("shuru:")
    try:#主代码
    num = int(inp)
    l1[999]

    except ValueError as e:#主代码异常
    print('no0')
    except IndexError as e:
    print("no1")
    except Exception as e:
    print(e)
    else:#主代码执行完执行
    print("ok1")
    finally:
    #无论异常与否都执行
    print("over")
    try:
    raise Exception('主动出错') # 创建一个exception对象,
    except Exception as e:
    print(e)
    #__str__方法,返回一个值
    class s(Exception):
    def __init__(self):
    pass
    def __str__(self):
    return "ok"
    try:
    raise s()
    except s as e:
    print(e)
    assert 1 == 1#断言,成立就成立,不成立就报错
  • 相关阅读:
    Understanding about Baire Category Theorem
    Isometric embedding of metric space
    Convergence theorems for measurable functions
    Mindmap for "Principles of boundary element methods"
    Various formulations of Maxwell equations
    Existence and uniqueness theorems for variational problems
    Kernels and image sets for an operator and its dual
    [loj6498]农民
    [luogu3781]切树游戏
    [atAGC051B]Three Coins
  • 原文地址:https://www.cnblogs.com/currynashinians000/p/8677577.html
Copyright © 2011-2022 走看看