Python進階---面向對象第三彈(進階篇)
Python對象中一些方法
一、__str__
class Teacher:
def __init__(self,name,age):
self.name=name
self.age=age
self.courses=[]
def teach(self):
print(‘%s teach‘ %self.name)
def __str__(self):
return ‘<name:%s age:%s>‘ %(self.name,self.age)
class Course:
def __init__(self,name,price,period):
self.name=name
self.price=price
self.period=period
def __str__(self):
return ‘《name:%s price:%s period:%s》‘ %(self.name,self.price,self.period)
# egon=Teacher(‘egon‘,18)
# print(egon) #egon.__str__()
# print(egon) #egon.__str__()
二、__del__用法
import time
# class Foo:
# def __init__(self,x):
# self.x=x
# print(‘connect mysql‘) #conn=abcdef(‘192.168.1.10‘,3306)
#
# def __del__(self):
# ‘‘‘做一些與這個對象有關的清理操作‘‘‘
# # conn.close()
# # file.close()
# print(‘====>‘)
# f=Foo(10)
# del f #f.__del__()
# time.sleep(3)
# print(‘主程序‘)
三、item用法
可以實現類於dic[‘a‘]這樣的方法
# l=[‘a‘,‘b‘,‘c‘]
# dic={‘a‘:1}
#
# print(l[1])
# print(dic[‘a‘])
class Foo:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def __getitem__(self, item):
# print(self,item,type(item))
# return getattr(self,item)
return self.__dict__[item]
def __setitem__(self, key, value):
# setattr(self,key,value)
self.__dict__[key]=value
def __delitem__(self, key):
# delattr(self,key)
self.__dict__.pop(key)
def __len__(self):
return 10
f=Foo(‘egon‘,18,‘male‘)
# print(f.name) #f[‘name‘]
# print(f.age) #f[‘age‘]
# print(f.sex) #f[‘sex‘]
# print(f[‘name‘])
# f[‘name‘]=‘egon_nb‘
# print(f.__dict__)
# del f[‘name‘]
# print(f.__dict__)
print(len(f))
四、isinstance和issubclass
isinstance(obj,cls)檢查是否obj是否是類 cls 的對象
class Foo(object):
pass
obj = Foo()
isinstance(obj, Foo)
issubclass(sub, super)檢查sub類是否是 super 類的派生類
class Foo(object):
pass
class Bar(Foo):
pass
issubclass(Bar, Foo)
五、反射
class Teacher:
# school=‘oldboy‘
# def __init__(self,name,age):
# self.name=name
# self.age=age
#
# def teach(self):
# print(‘%s teach‘ %self.name)
# print(Teacher.school)
# print(Teacher.__dict__[‘school‘])
# print(hasattr(Teacher,‘school‘))
# print(getattr(Teacher,‘school‘))
# print(getattr(Teacher,‘solasdf‘,None))
# Teacher.x=123
# setattr(Teacher,‘x‘,123)
# print(Teacher.x)
# delattr(Teacher,‘school‘)
# print(Teacher.school)
#對象
# t=Teacher(‘egon‘,18)
# print(hasattr(t,‘name‘))#判斷對象是否有name屬性(“以字符串的方式”)
# print(getattr(t,‘name‘))#獲取對象的name屬性(“以字符串的方式”)
# setattr(t,‘sex‘,‘male‘)#修改對象的sex屬性(“以字符串的方式”)
# print(getattr(t,‘sex‘))
#
# print(t.__dict__)
# delattr(t,‘name‘)
# print(t.__dict__)
# t.teach()
# print(t.school)
# print(getattr(t,‘teach‘))
# print(getattr(t,‘school‘))
# t.school=‘hahahahahahahahahhahahahahahhahahahahahahh‘
# print(t.__dict__)
Python進階---面向對象第三彈(進階篇)