#-*- 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)

												

最新文章

  1. 暑假前的flag
  2. Velocity(5)——#set指令
  3. C语言初学者代码中的常见错误与瑕疵(15)
  4. JS模板引擎 :ArtTemplate (2)
  5. C#之父 Anders Hejlsberg
  6. Extjs 4 chart自定义坐标轴刻度
  7. 使用text-overflow:ellipsis对溢出文本显示省略号有两个好处
  8. C#可以直接调用的Win32API(和VCL做的整理工作非常类似)
  9. (转载)php的类中可以不定义成员变量,直接在构造方法中使用并赋值吗?
  10. Js apply call方法详解
  11. Linux 安装Anaconda 4.4.0
  12. 为什么选择Netty作为基础通信框架?
  13. 前端知识点总结——VUE
  14. 一个有关FWT&amp;FMT的东西
  15. Axis2开发WebService客户端 的3种方式
  16. English trip V1 - B 21. On a busy day 忙碌的一天 Teacher:Taylor Key: at on in
  17. PLSQL Developer概念学习系列之登录连接Oracle时出现(没有登录) -PL / SQL Developer:ORA - 12541: TNS :无建听程序的错误解决办法(图文详解)
  18. VMware Workstation 12 OpenGL ES版本支持情况与设置
  19. C# - 反射与编译
  20. HTTP协议响应消息的常用状态码【转】

热门文章

  1. CentOS安装NodeJS v0.10.25 + Express
  2. 第8章 委托、Lamdba表达式和事件
  3. C++Primer 第三章
  4. SQL百分比
  5. poj 1417(并查集+简单dp)
  6. editPlus修改默认的文件编码
  7. strcpy  复制字符串函数
  8. JSon_零基础_004_将Set集合对象转换为JSon格式的对象字符串,返回给界面
  9. struts_22_xwork校验器列表使用说明
  10. ef 5 在 DropCreateDatabaseAlways 报错,the connection is currently used