2.6
python
#获取对象信息
#type
print(type(123))
#<class 'int'>
#变量指向函数类
print(type(abs))
#<class 'builtin_function_or_method'>
#使用isinstance相对于继承关系 isinstance简便
class Animal(object):
def run(self):
print("Animal is running")
class Dog(Animal):
def run(self):
print("Dog is running")
class Husky(object):
def run(self):
print('Car is running...')
a=Animal()
d=Dog()
h=Husky()
isinstance(h,Animal)#True
#使用dir() 获取全部
print(dir('ABC'))
#['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
#属性测试
class MyObject(object):
def _init_(self):
self.x=9
def power(self):
return self.x*self.x
obj=MyObject
hasattr(obj,'x')
def readImage(fp):
if hasattr(fp,'read'):
return read Data(fp)#无须关心内部,会自动根据fp的对象类型去执行各自的read方法
return None
class MyObject(object):
def _init_(self):
self.x=9
def power(self):
return self.x*self.x
obj=MyObject
hasattr(obj,'x')
print('hasattr(obj,\'y\')=', hasattr(obj, 'y'))
setattr(obj,'y',19)#设置y
print('hasattr(obj,\'y\')=',hasattr(obj,'y'))
print('getattr(obj,\'y\')=',getattr(obj,'y'))#获取
print('obj.y=',obj.y)
f=getattr(obj,'power')#获取power
print(f)
print(f())
#实例属性和类属性
class Student(object):
def __init__(self,name):
self.name=name
s=Student('Bob')
s.score=90
#给student 绑定属性 类属性
class Student(object):
name='Student'
s=Student()#创建实例s
print(s.name)
s.name='Michael'#给实例绑定name属性
print(s.name)#Michael 实例属性优先级比类属性高
del s.name#如果删除实例的name属性
print(s.name)#再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
#因为已经删除 实例name属性未删除 类name属性显示
class Student(object):
count=0
def __init__(self,name):
self.name=name#每次增加name属性
Student.count=Student.count+1
if Student.count!=0:
else:
bart=Student('Bart')
if Student.count!=1:
#Student类增加一个类属性,每创建一个实例,该属性自动增加: