zoukankan      html  css  js  c++  java
  • Python类的构造方法及继承问题

    构造方法名字固定为__init__,在创建对象时会自动调用,用于实现类的初始化:

    >>> class Person:
    ...     def __init__(self, name, age=0):
    ...             self.name = name
    ...             self.age = age
    ...     def get_name(self):
    ...             return self.name
    ...     def set_name(self, name):
    ...             self.name = name
    ...     def get_age(self):
    ...             return self.age
    ...     def set_age(self, age):
    ...             self.age = age
    ...
    >>> p = Person('韩晓萌','21')
    >>> p.get_name()
    '韩晓萌'
    >>> p.get_age()
    '21'
    >>>

    如果子类重写了__init__方法,那么在方法内必须显式的调用父类的__init__方法:

    # 没有调用父类的__init__方法
    >>> class Man(Person): ... def __init__(self, length): ... self.length = length ... def get_length(self): ... return self.length ... def set_length(self, length): ... self.length = length ... >>> m = Man('18cm') >>> m.get_length() '18cm' >>> m.get_name() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in get_name AttributeError: 'Man' object has no attribute 'name' # 调用了父类的__init__方法 >>> class Woman(Person): ... def __init__(self, name, age=0, cup='A'): ... super().__init__(name, age) ... self.cup = cup ... def get_cup(self): ... return self.cup ... def set_cup(self, cup): ... self.cup = cup ... >>> w = Woman('杨超越', 21, 'C') >>> w.get_cup() 'C' >>> w.get_name() '杨超越' >>> w.get_age() 21
  • 相关阅读:
    轮播 margin-left实现
    点击按钮切换图片
    运用把不同的方式排版,涉及到float box-flox box-orient
    chrome中font-size<12px时并不更改字体大小仍未12px
    js实现跑马灯
    支付宝支付集成
    前端技术博客
    在iphone5/5s出现界面显示不全,大小为iphone4/4s 的问题
    UIImage使用总结
    在IOS开发中使用自定义的字体
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711081.html
Copyright © 2011-2022 走看看