python多态笔记整理
2017-12-30 18:23
309 查看
多态
1.类属性:属于类的成员,属于对象共有的
2.方法:在方法上添加@classmethod
@classmethod
def cmethod(cls):
print("这是一个类方法...............")
可以通过类方法分调用类属型,也可以通过对象调用类属型
3.静态方法:方法前加@staticemethod静态方法没有参数,静态方法即和类没关系,也和对象没有关系,也可以通过类和对象调用
@staticmethod
def smethod():
print("这是一个静态方法")
1. __new__(cls):用来创建对象,而且必须有返回值
return object.__new__(cls)
当有属性时需在__new__()中也添加属性
2. 单例
class singlethon:
__instance=None
def __new__(cls, *args, **kwargs):
if cls.__instance==None:
cls.__instance=object.__new__(cls)
return cls.__instance
else:
return cls.__instance
s=singlethon()
ss=singlethon()
print(id(s))
print(id(ss)) 输出时两个地址一样
--------------------------------------------------------------------------
用愤怒的小鸟举一个多态例子
1.类属性:属于类的成员,属于对象共有的
2.方法:在方法上添加@classmethod
@classmethod
def cmethod(cls):
print("这是一个类方法...............")
可以通过类方法分调用类属型,也可以通过对象调用类属型
3.静态方法:方法前加@staticemethod静态方法没有参数,静态方法即和类没关系,也和对象没有关系,也可以通过类和对象调用
@staticmethod
def smethod():
print("这是一个静态方法")
1. __new__(cls):用来创建对象,而且必须有返回值
return object.__new__(cls)
当有属性时需在__new__()中也添加属性
2. 单例
class singlethon:
__instance=None
def __new__(cls, *args, **kwargs):
if cls.__instance==None:
cls.__instance=object.__new__(cls)
return cls.__instance
else:
return cls.__instance
s=singlethon()
ss=singlethon()
print(id(s))
print(id(ss)) 输出时两个地址一样
--------------------------------------------------------------------------
用愤怒的小鸟举一个多态例子
class brid: 父类 def __init__(self,name,cut): self.name=name self.shout="嗷嗷叫" self.cut=cut self.fly="弹射飞" class fln(brid): 继承父类的方法 子类可以重写父类的方法 def method(self): self.name="分裂鸟" self.cut="攻击:分裂攻击" print("%s %s %s %s" % (self.name, self.shout, self.cut,self.fly)) class hjn(brid): def method(self): self.name="火箭鸟" self.cut="攻击:加速冲撞" print("%s %s %s %s" % (self.name, self.shout, self.cut,self.fly)) class redn(brid): def method(self): self.name="红色鸟" self.shout="渣渣叫" self.cut="攻击:普通攻击" print("%s %s %s %s" % (self.name, self.shout, self.cut,self.fly)) class zdn(brid): def method(self): self.name="炸弹鸟" self.shout="渣渣叫" self.cut="攻击:爆炸攻击" print("%s %s %s %s" % (self.name, self.shout, self.cut,self.fly)) class pangn(brid): def method(self): self.name="胖子鸟" self.shout="不叫" self.cut="攻击:扔蛋" print("%s %s %s %s"%(self.name,self.shout,self.cut,self.fly)) a=fln(" ", " ") a.method() b=hjn(" ", " ") b.method() c=redn(" ", " ") c.method() d=zdn(" ", " ") d.method() e=pangn(" ", " ") e.method()
相关文章推荐
- python 学习笔记整理
- Python学习笔记整理(十四)类基础
- python类和对象笔记整理
- Python笔记整理(3)
- Python学习笔记整理(十)Python的if测试
- Python学习笔记整理(十七)异常处理
- appium python andiroid自动化文档整理笔记
- python学习笔记8-函数整理
- python学习笔记17-常用函数总结整理
- Python开发【整理笔记】
- Python学习笔记整理(十一)Python的while和for循环
- python学习笔记---多态
- DAY6之Python学习笔记:面向对象术语整理
- python学习简要笔记整理
- Python学习笔记整理(python 3)
- Java笔记整理——接口、继承与多态
- Python学习笔记之报错整理
- 黑马程序员-----笔记整理(java基础五-------面向对象--多态)
- Python学习笔记整理(二)python的数字
- Python笔记-类和实例、继承和多态