看代码:
class test_has:
def print_a(self):
print "a"
if hasattr(test_has , 'print_a'):
print "test_has object have attribute print_a"
if isinstance(test_has , object):
print "test_has is a object"
test_has object have attribute print_a
test_has is a object
a_string = "hello world"
str_list = a_string.split()
print str_list
if hasattr(str_list , "append") and isinstance(str_list, list):
print "the right"
['hello' , 'world']
the right
关于hasattr , setattr,delattr等的应用,还是看例子比较好:
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def __setattr__(self, name, value):
if name == 'size':
self.width, self.height = value
else:
self.__dict__[name] = value
def __getattr__(self, name):
if name == 'size':
return self.width, self.height
else:
raise AttributeError
def __str__(self):
return str(self.width)+' '+str(self.height)
t_class = Rectangle()
t_class.name="size"
t_class.size = [12, 13]
print t_class.size
print t_class.width
print t_class.height
print t_class
输出是:
(12, 13)
12
13
12 13
setattr对应的是给对象设置属性,getattr对应的是获得对象的属性。
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def __setattr__(self, name, value):
if name == 'size':
self.width, self.height = value
else:
self.__dict__[name] = value
def __getattr__(self, name):
if name == 'size':
return self.width, self.height
else:
raise AttributeError
def __str__(self):
return str(self.width)+' '+str(self.height)
t_class = Rectangle()
setattr(t_class , "name","size")
print t_class.name
setattr(t_class, "size" , [12,13])
print t_class.size
print t_class
输出和上面一样
#-*- coding:utf-8 -*-
class storage(dict):
#通过使用__setattr__, __getattr__, __delattr__
#可以重写dict,使之通过“.”调用
def __setattr__(self, key, value):
self[key] = value
def __getattr__ (self, key):
try:
return self[key]
except KeyError, k:
return None
def __delattr__ (self, key):
try:
del self[key]
except KeyError, k:
return None
# __call__方法用于实例自身的调用
#达到()调用的效果
def __call__ (self, key):
try:
return self[key]
except KeyError, k:
return None
s = storage()
s.name = "hello"#这是__setattr__起的作用
print s("name")#这是__call__起的作用
print s["name"]#dict默认行为
print s.name#这是__getattr__起的作用
del s.name#这是__delattr__起的作用
print "-"*20
print s("name")
print s["name"]
print s.name