面向对象进阶
一、成员修饰符
1、公有成员:字段名
实例:
class Foo:
def __init__(self,name,age):
self.name=name # 定义公有字段
self.age=age
def show(self):
print(self.name)
print(self.age)
obj=Foo('lh','18')
obj.show()
2、私有成员: __字段名
实例:
class Foo:
def __init__(self):
self.gender = 'man' # 定义公有字段
self.__gene = 123 # 定义私有字段
class S(Foo):
def __init__(self, name):
self.name = name
self.__age = 123 # 私有字段只存在在本类中,任何其他类不能访问
super(S, self).__init__() #调用基类中的__init__方法
def show(self):
print(self.name)
print(self.gender)
print(self.__age)
# print(self.__gene) # 派生类不能访问基类中的私有字段
obj = S('lh')
obj.show()
二、特殊成员
1、__init__
实例:
class Foo:
def __init__(self,name,age):
self.name=name
self.age=age
obj=Foo('lh','18') # 自动执行__init__方法
2、__call__
实例:
class Foo:
def __call__(self, *args, **kwargs):
print('call')
# Foo()() # 类名()().自动执行__call__方法
obj=Foo()
obj() # 对象(),自动执行__call__方法
3、__int__
实例:
class Foo:
def __int__(self): # int(对象),自动执行__int__方法
return 1
obj=Foo()
ret=int(obj)
print(ret)
4、__str__
实例:
class Foo: def __str__(self): return 2 obj=Foo() ret=str(obj) # str(对象),自动执行__str__方法 print(ret)
5、__getitem__
实例:
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __getitem__(self, item):
return item
li = Foo('lh', '18')
ret1 = li[2] # 调用__getitem__方法,返回结果为2
print(ret1)
9、__setitem__
实例:
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __setitem__(self, key,value):
print(key,value)
li = Foo('lh', '18')
li[2] = 'lh' #调用__setitem__方法(设置key和value值)
10、__delitem__
实例:
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __delitem__(self, key):
print(key)
del li[1] #调用__delitem__方法
11、__iter__
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __iter__(self):
return iter([11, 22, 33])
obj = Foo('lh', 18)
for i in obj: # 调用__iter__方法,先转换成迭代器,再进行循环
print(i)
12、__dict__
实例:
class Province:
def __init__(self,name,count):
self.name=name
self.count=count
obj=Province('河北','10000')
print(obj.__dict__) # 以字典格式输出
三、metaclass,类的祖宗
1、 Python中一切事物都是对象
2、
class Foo:
pass
obj = Foo()
# obj是Foo类的对象
# Foo类是type的对象
3、 类都是type类的对象 type(..),“对象”都是以类的对象 类()
四、异常处理
实例1:
try:
r1=int('weq') # 只要有一个错误,下边代码就不会执行
# li=[11,22,33]
# r2=li[444]
# ret=int('111')
except IndexError as e:
print('IndexError')
except ValueError as e:
print('ValueError')
except Exception as e:
print('有错误')
else: # try代码块中没错时,执行本代码
print('正确')
finally: # 不管从程序有没有错误,最后都会执行本代码
print('666')
实例2:
class LhError(Exception): # 自己定义错误
def __init__(self,msg):
self.message=msg
def __str__(self):
return self.message
try:
raise LhError('错误!') # 主动捕获异常
except LhError as e:
print(e) # 打印错误信息
print(123)
assert 1==1 # 必须满足assert条件,下边代码才会执行
print(456)
五、反射
1、方法
# 通过字符串的形式操作对象中的成员
class Foo:
def __init__(self,name,age):
self.n=name
self.a=age
def show(self):
print(self.n,self.a)
obj=Foo('lh',18)
func=getattr(obj,'show') # 获取对象中的方法
func()
print(getattr(obj,'n')) # 获取对象中的数据
print(hasattr(obj,'name')) # 判断对象中是否有这个数据
setattr(obj,'gender','男') # 在对象中添加数据
print(obj.gender)
delattr(obj,'gender') # 在对象中删除数据
2、实例
# s2文件:
def f1():
return '首页'
def f2():
return '新闻'
def f3():
return '关注'
# 主文件:
import s2
while True:
inp = input('请输入您要进入的页面:')
if hasattr(s2, inp): # 判断在f2中是否有输入的函数
func = getattr(s2, inp) # 创建输入的函数的对象
ret = func() # 执行函数
print(ret)
elif inp == 'q':
break
else:
print('您输入错误!')
六、单例模式
实例:
class Foo:
__v = None
@classmethod
def get_instance(cls):
if cls.__v==None: # 如果cls._instance不为None,直接返回cls._instance
return cls.__v
else: # 如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回
cls.__v = Foo()
return cls.__v
ret = Foo.get_instance()
print(ret)
ret = Foo.get_instance()
print(ret)
ret = Foo.get_instance()
print(ret)
posted on 2016-09-27 11:28 python屌丝的逆袭 阅读(229) 评论(0) 收藏 举报
浙公网安备 33010602011771号