# 抽象类或者接口类,制定规范,统一方法名
# # 抽象类或者接口类,制定规范,统一方法名
from abc import ABCMeta,abstractmethod
class Payrole(metaclass=ABCMeta):
@abstractmethod
def pay(self,money):pass class QQpay(Payrole):
def pay(self,money):
print('您已经通过QQ支付了%s元' % money) class Wechatpay(Payrole):
def pay(self,money):
print('您已经通过微信支付了%s元' % money) class Alipay(Payrole):
def pay(self, money):
print('您已经通过支付宝支付了%s元' % money) def pay(obj,money):
obj.pay(money) qq = QQpay()
weixin = Wechatpay()
ali = Alipay()
pay(qq,700)
pay(weixin,600)
pay(ali,400)
pay(ali,900)
# 将方法转换为属性,修改和删除私有方法
# 将方法转换为属性,修改和删除私有方法 class People:
def __init__(self, name, age, sex):
self.name = name
self.__age = age
self.__sex = sex
@property
def age(self):
return self.__age @age.setter
def age(self,new_age):
self.__age = new_age @age.deleter
def age(self):
return 789 a = People('anthony',19,'男')
# a.age = 21
del a.age
print(a.age)
# 反射(实例化对象、类、当前模块、其他模块)
# 对于实例化对象
class Foo:
f = '类的静态变量'
def __init__(self,name,age):
self.name=name
self.age=age def say_hi(self):
print('hi,%s'%self.name) obj=Foo('egon',73) print(hasattr(obj,'name')) # 判断属性是否存在
print(getattr(obj,'name')) # 获取属性 setattr(obj,'oldboy','anthony') # 修改属性
print(getattr(obj,'oldboy')) print(delattr(obj,'name')) # 删除属性
print(getattr(obj,'name'))
实例化对象示例
# 对于类的示例
class Foo(object):
staticField = "old boy" def __init__(self):
self.name = 'wupeiqi' def func(self):
return 'func' @staticmethod
def bar():
return 'bar' print(getattr(Foo,'staticField'))
print(getattr(Foo,'bar'))
类的示例
# 对于当前模块的示例
import sys def s1():
print( 's1') def s2():
print( 's2') this_module = sys.modules[__name__] print(getattr(this_module,'s1'))
print(hasattr(this_module,'s2'))
当前模块的示例
#一个模块中的代码
def test():
print('from the test')
"""
程序目录:
module_test.py
index.py 当前文件:
index.py
"""
# 另一个模块中的代码
import module_test as obj #obj.test() print(hasattr(obj,'test')) getattr(obj,'test')()
其他模块的示例