python7 静态方法类方法属性方法 ;反射;异常处理
Posted 一个人的北京
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python7 静态方法类方法属性方法 ;反射;异常处理相关的知识,希望对你有一定的参考价值。
#-*- coding:utf8 -*- # 静态方法@staticmethod # 静态方法(当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。) class Dog(object): def __init__(self, name): self.name = name #@staticmethod # 静态方法(当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。) def eat(self): print("%s is eating" % self.name) d = Dog("ChenRonghua") d.eat() #报错信息 #TypeError: eat() missing 1 required positional argument: \'self\'
# 类方法 # 类方法通过@classmethod装饰器实现,类方法只能访问类变量,不能访问实例变量 # (当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。) class Dog(object): def __init__(self, name): self.name = name @staticmethod def eat(): print("%s is eating")#因为name是个实例变量,类方法是不能访问实例变量的 d = Dog("ChenRonghua") d.eat()
class Dog(object): name = "我是类变量" def __init__(self, name): self.name = name self.__food=None @classmethod def eat(self): print("%s is eating" % self.name) def __call__(self, *args, **kwargs):#构造方法:对象=类名() 而__call__ 则是:对象() print("running call",args,kwargs) def __str__(self): return \'obj:%s\'%self.name d = Dog("ChenRonghua") d(2,3,4,name=\'开发量\')#__call__ 则是:对象() print(d.__dict__)#打印的是实例属性{\'name\': \'ChenRonghua\', \'_Dog__food\': None} print(Dog.__dict__)#打印的是类的属性 print(d)#module对象想知道它是谁__str__ d.eat() #把一个类做成字典了
#属性方法 #属性方法的作用就是通过@property把一个方法变成一个静态属性 class Dog(object): \'\'\' 类是描述狗这个对象\'\'\' def __init__(self, name): self.name = name @property def eat(self): print(" %s is eating" % self.name) d = Dog("ChenRonghua") print (Dog.__doc__) #d.eat() #因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了 d.eat
#@property 的实例---航班查询 #这个status属性的值是一系列动作后才得到的结果 class fly(object): def __init__(self,name): self._name=name def check_status(self): print("%s fly status"%self._name) return 2 @property def fly_status(self): status=self.check_status() if status==0: print ("quxiao") elif status==1: print("daoda") elif status == 2: print("ready") else: print("later") d=fly("k7") d.fly_status #-----------另一种 class fly(object): def __init__(self,name): self._name=name def check_status(self): print("%s fly status"%self._name) return 2 def fly_status(self): status=self.check_status() if status==0: print ("quxiao") elif status==1: print("daoda") elif status == 2: print("ready") else: print("later") d=fly("k7") d.fly_status()
#__doc__表示类的描述信息 class Foo: """ 描述类信息,这是用于看片的神奇 """ def func(self): pass print(Foo.__doc__)
#__call__对象后面加括号 #构造方法,即:对象 = 类名() ; #__call__方法 即:对象() 或者 类()() class Foo: def __init__(self): print("__init__") def __call__(self, *args, **kwargs): print(\'__call__\') obj = Foo() # 执行 __init__ obj() # 执行 __call__
#如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值 class Foo: def __str__(self): return \'alex li\' obj = Foo() print(obj)
#生命的起源是通过Type来实现的 def func(self): print ("hello %s"%self.name) def __init__(self,name,age): self.name=name self.age=age foo=type("foo",(object,),{"talk":func, "__init__":__init__}) f =foo("alex",32) f.talk() print(type(foo)) #<class \'type\'>
#-*- coding:utf8 -*- class Dog(): def __init__(self,name): self.name=name def eat(self): print ("%s is eating..."%self.name) d=Dog("zhangsan") choice=input(">>:").strip() # print (hasattr(d,choice))#>>:eat---True # getattr(d,choice)() #zhangsan is eating... if hasattr(d,choice): func=getattr(d,choice) func()
#-*- coding:utf8 -*- def dulk(self): print("%s is yelling.."%self.name) class Dog(): def __init__(self,name): self.name=name def eat(self,food): print ("%s is eating..."%self.name,food) d=Dog("zhangsan") choice=input(">>:").strip() # print (hasattr(d,choice))#>>:eat---True # getattr(d,choice)() #zhangsan is eating... if hasattr(d,choice): func=getattr(d,choice) func("lisi") #>>:eat --zhangsan is eating... lisi #hasattr (obj,name_str)判断一个对象是否有对应的name_str字符串的 #getattr(obj,name_str)根据字符串去获取对象对应方法里的内存地址 else : # setattr(d,choice,dulk) # d.talk(d) setattr(d,choice,32) print(getattr(d,choice)) #>>:talk --32
#-*- coding:utf8 -*- def dulk(self): print("%s is yelling.."%self.name) class Dog(): def __init__(self,name): self.name=name def eat(self,food): print ("%s is eating..."%self.name,food) d=Dog("zhangsan") choice=input(">>:").strip() # print (hasattr(d,choice))#>>:eat---True # getattr(d,choice)() #zhangsan is eating... if hasattr(d,choice): getattr(d,choice) else : # print(setattr(d,choice,None)) setattr(d,choice,dulk) func=getattr(d,choice) func(d)
#-*- coding:utf8 -*- def dulk(self): print("%s is yelling.."%self.name) class Dog(): def __init__(self,name): self.name=name def eat(self,food): print ("%s is eating..."%self.name,food) d=Dog("zhangsan") choice=input(">>:").strip() # print (hasattr(d,choice))#>>:eat---True # getattr(d,choice)() #zhangsan is eating... if hasattr(d,choice): func=getattr(d,choice) setattr(d ,choice,"xiaobai") # func("lisi") #>>:eat --zhangsan is eating... lisi #hasattr (obj,name_str)判断一个对象是否有对应的name_str字符串的 #getattr(obj,name_str)根据字符串去获取对象对应方法里的内存地址 else : # setattr(d,choice,dulk) # d.talk(d) setattr(d,choice,32) print(getattr(d,choice)) print(d.name) #>>:name----xiaobai #setattr (obj,\'y\',z) is equitvalent to x.y=z 对对象添加新的属性
异常处理
#-*- coding:utf8 -*- #---字典出错,列表出错 data={} names=[\'zhangsan\',\'lisi\'] # data[\'name\'] #KeyError: \'name\' try: names[3] #这个报错,下一个错误就不会执行了 data[\'name\'] except KeyError as e: print(\'没有这个key\',e) except IndexError as e: print("列表操作错误", e)
try_未知错误-Exception最后用
data={} names=[\'zhangsan\',\'lisi\'] # data[\'name\'] #KeyError: \'name\' try: open("test.txt") names[3] # 如果它放在try的第一位 就不报未知错误 data[\'name\'] except KeyError as e: print(\'没有这个key\',e) except IndexError as e: print("列表操作错误", e) except Exception as e: #错误排除不出来,最后报未知错误 print ("未知错误",e )
ValueError
#-*- coding:utf8 -*- s1="hello" try: int(s1) except ValueError as e: print ("类型不正确",e)
两种错误都采用统一的处理办法
#-*- coding:utf8 -*- #---字典出错,列表出错 data={} names=[\'zhangsan\',\'lisi\'] # data[\'name\'] #KeyError: \'name\' try: names[3] #这个报错,下一个错误就不会执行了 data[\'name\'] except (KeyError ,IndexError) as e: print(\'没有这个key\',e) # except IndexError as e: # print("列表操作错误", e)
自定义异常
#-*- coding:utf8 -*- #__str__类返回什么格式 class flmException(Exception): def __init__(self,msg): self.message=msg # def __str__(self): # return self.message #替换为 return "abc" try: raise flmException("数据库连不上") except flmException as e: print(e)
以上是关于python7 静态方法类方法属性方法 ;反射;异常处理的主要内容,如果未能解决你的问题,请参考以下文章