静态方法:
@staticmethod,只是名义上归类管理,实际上在静态方法里访问不了类或者实例的任何属性
类方法:
@classmethod,只能访问类变量,不能访问实例变量
属性方法:
@property ,把一个方法变成一个静态属性
属性方法的应用如下: f.flight_status调用属性方法,.setter 进行修改,.deleter进行删除
__author__ = 'admin'
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 1
@property
def flight_status(self):
status = self.checking_status()
if status == 0 :
print("flight got canceled...")
elif status == 1 :
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter #修改
def flight_status(self,status):
status_dic = {
0 : "canceled",
1 :"arrived",
2 : "departured"
}
print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) )
@flight_status.deleter #删除
def flight_status(self):
print("status got removed...")
f = Flight("CA980")
f.flight_status
f.flight_status = 2 #触发@flight_status.setter
del f.flight_status #触发@flight_status.deleter
运行结果如下:
checking flight CA980 status
flight is arrived...
Has changed the flight status to departured
status got removed...
类的特殊成员方法
1.1 1. doc 表示类的描述信息
class Foo:
""" 描述类信息,这是用于看片的神奇 """
def func(self):
pass
print Foo.__doc__
输出:类的描述信息
1.2 module 和 class 表示当前操作的对象在那个模块 和表示当前操作的对象的类是什么
from lib.aa import C
obj = C()
print (obj.__module__ ) # 输出 lib.aa,即:输出模块
print (obj.__class__ ) # 输出 lib.aa.C,即:输出类
1.3. init 构造方法,通过类创建对象时,自动触发执行。
1.4. del 析构方法,当对象在内存中被释放时,自动触发执行。
1.5. call 对象后面加括号,触发执行。需要先定义__call__方法
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print '__call__'
obj = Foo() # 执行 init
obj() # 执行 call
1.6 . dict 查看类或对象中的所有成员
print(Foo.__dict__) 返回类的属性
print(obj.__dict__) 返回实例的属性
1.7 str 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
class Foo:
def str(self):
return 'alex li'
obj = Foo()
print( obj )
输出:alex li
1.8.__getitem__、setitem、delitem 需要先定义它们的方法
class Foo(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
obj = Foo()
result = obj['k1'] # 自动触发执行 getitem
obj['k2'] = 'alex' # 自动触发执行 setitem
del obj['k1']
1.9 new metaclass #方法__new__用来实例化对象 , metaclass,其用来表示该类由 谁 来实例化创建,可以为 metaclass 设置一个type类的派生类,从而查看 类 创建的过程:类的生成 调用 顺序依次是 MyType.__init__ -->MyType.__call__ --> Foo.__new__ --> Foo.__init__
类class Foo的特殊定义方法:
def func(self):
print 'hello wupeiqi'
Foo = type('Foo',(object,), {'func': func})
type第一个参数:类名
type第二个参数:当前类的基类
type第三个参数:类的成员
class MyType(type):
def init(self,*args,**kwargs):
print("Mytype __init__",*args,**kwargs)
def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj
def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)
print('here...')
class Foo(object,metaclass=MyType):
#metaclass = MyType
def __init__(self,name):
self.name = name
print("Foo __init__")
def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)
f = Foo("Alex")
print("f",f)
print("fname",f.name)
1.10 反射
hasattr(obj,y) 判断对象是否有属性'y',返回True或False
getattr(obj,y) 获取对象方法y的地址或者属性y的值
setattr(obj,y,v) 设置对象的obj.y=v
delattr(obj,y) 删除对象的属性y
__author__ = 'admin'
def eat(self):
print('eating')
class Foo(object):
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
choice = input('>>:').strip()
d = Foo()
if hasattr(d,choice):
attr = getattr(d,choice)
print(attr())
else:
setattr(d,choice,eat) #add new attr 'eat'
getattr(d,choice)(d) #将obj本身作为方法eat的参数进行调用
# setattr(d,choice,"name1") #新增属性 d.choice = 'name1'
# print(hasattr(d,choice))
# print(getattr(d,choice)) #getattr(d,choice)直接新增的属性的值
2 异常处理
2.1 异常提示
try:
#s1 = 'hello'
#int(s1)
name = []
name[2]
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
except Exception as e :
print(e)
else:
print('unknown error')
finally:
print(66)
2.2 自定义异常,主动触发
class WupeiqiException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise WupeiqiException('我的异常')
except WupeiqiException as e:
print(e)