zoukankan      html  css  js  c++  java
  • 【学习整理】第九章节 魔法方法,属性和迭代器

    一、构造器
    1、无参数构造
    class FooBar:
    def __init__(self): # 构造函数前后两个下划线
    self.somevar = 42
    2、代参构造:
    class FooBar:
    def __init__(self,value=42): #这个参数是默认值,不传值默认为42 传值就会被覆盖
    self.somevar = value
    创建对象的时候这样使用:
    f=FooBar('this is a constructor argument')
    f.somevar
    'this is a constructor argument '
     
    3、与构造方法相对应的一个析构方法 是该对象被垃圾回收之前调用的方法
    由于调用该方法的具体时间不可知,所以该方法慎用;
    二、调用父类的构造方法
    class Bird:
    def __init__(self):
    self.hungry = True
    def eat(self):
    if self.hungry:
    pritnt 'Aaaaah....'
    self.hungry = False
    else:
    print 'No,thanks'
    class SongBird(Brid):
    def __init__(self):
    #Brid.__init__(self) 方式一:老式的调用父类的方法
    super(SongBird,self).__init__() #方式二:通过这种方式调用父类的构造方法
    self.sound = "Squawk"
    def sing(self):
    print self.sound
     
  • 相关阅读:
    Nginx配置文件的路径
    有关Tomcat 8.5版本文件上传后无权限访问的问题
    常见HTTP状态码列表
    服务器BMC(带外)
    CDN问题
    PECE
    linux系统概述
    干货--整蛊你的舍友
    arp请求与回复
    huawei oceanstor
  • 原文地址:https://www.cnblogs.com/xujie09/p/7138167.html
Copyright © 2011-2022 走看看