标签:方法 com 继承 循环 any 重复 判断 def oid
面向对象的三大特性:封装、继承、多态
方法封装到类中
class File: def file_add():pass def file_update():pass def file_del():pass def file_fetch():pas
将数据封装到对象中
class File: def __init__(self,name,age,email): self.name = name self.age = age self.email = email def file_add():pass def file_update():pass def file_del():pass def file_fetch():pass obj1 = File(‘oldboy‘,19,"asdf@live.com") obj2 = File(‘oldboy1‘,119,"asdf12@live.com")
应用:
如果多个类中有相同的方法,为了避免重复编写可以将其放在父类(基类)中
class Base(object): def xxxx():pass class File(Base): def __init__(self,name,age,email): self.name = name self.age = age self.email = email def file_add():pass def file_update():pass def file_del():pass def file_fetch():pass class DB(Base): def db_add():pass def db_update():pass def db_del():pass def db_fetch():pass
应用:
多态(鸭子模型):天生支持多态,对于参数来说可以传入任何类型的对象,只要保证有想要的send方法即可。
class Msg(object): def send(): pass class WX(object): def send(): pass def func(arg): arg.send()
进阶
类里面常用的双下划线的方法
__init__
__new__
__call__
- 创建类时,先执行type的__init__。
- 类的实例化时,执行type的__call__,__call__方法的的返回值就是实例化的对象。
type的__call__方法内部调用:
- 类.__new__,创建对象
- 类.__init__,对象的初始化
类创建的两种方式:
#常用方式 class Foo(object): a1 = 123 def func(self): return 666 #type方式 Foo = type("Foo",(object,),{‘a1‘:123,‘func‘:lambda self:666}
如何指定类由自定义type创建
class MyType(type): pass class Foo(object,metaclass=MyType): # __metaclass__ = MyType # py2 pass Foo = MyType(‘Foo‘,(object,),{})
默认执行顺序
class Foo(object,metaclass=MyType): pass obj = Foo() class MyType(type): def __init__(self,*args,**kwargs): print(‘111‘) super(MyType,self).__init__(*args,**kwargs) class Base(object, metaclass=MyType): pass class Foo(Base): pass 如果类自己或基类中指定了metaclass,那么该类就是由metaclass指定的type或mytype创建。 #同: class MyType(type): def __init__(self,*args,**kwargs): print(‘111‘) super(MyType,self).__init__(*args,**kwargs) # class Base(object, metaclass=MyType): # pass Base = MyType(‘Base‘,(object,),{}) class Foo(Base): pass #同: class MyType(type): def __init__(self,*args,**kwargs): print(‘111‘) super(MyType,self).__init__(*args,**kwargs) # class Base(object, metaclass=MyType): # pass def with_metaclass(arg): Base = MyType(‘Base‘,(arg,),{}) return Base class Foo(with_metaclass(object)): pass
标签:方法 com 继承 循环 any 重复 判断 def oid
原文地址:https://www.cnblogs.com/weidaijie/p/10480256.html