• 【原】Python基础-__init__


    #py中,有些名称前后都会加上俩个下划线,是有特殊含义的
    #在Py中,由这些名字组成的集合所包含的方法称为 “魔法方法”。如果在你的对象中
    #实现了这些方法的其中某一个,那这些方法会被py自动调用,几乎没有必要自己调用。比如
    #构造方法,在类中定义 __init__就可以。
    class FooBar:
    var = "none"
    def __init__(self):
    self.var = "init var"

    f = FooBar()
    print(f.var)

    #构造方法有参数的情况
    class FooBar2:
    var = "none"
    def __init__(self, value):
    self.var = value

    f2 = FooBar2("sysnap xxxx")
    print(f2.var)

    #类的继承
    class ClassA:
    def hello(self):
    print("hello in class A")

    class ClassB(ClassA):
    pass
    a = ClassA()
    a.hello() #输出 hello in class A

    b = ClassB()
    b.hello() #输出hello in class A
    del a, b

    #类继承中,方法的重写
    class ClassA_1:
    def hello(self):
    print("hello class a")
    class ClassB_1(ClassA_1):
    def hello(self): #重写了a中的hello方法
    print("hello class b")
    a = ClassA_1()
    a.hello() #输出hello class a

    b = ClassB_1()
    b.hello() #输出hello class b

    #继承类中重写构造方法,有个问题,就是父类的构造方法不会被调用到,使用supper函数
    class Brid:
    def __init__(self):
    self.hungry = 1
    def eat(self):
    if self.hungry == 1:
    print("i am hungry! ")
    self.hungry = 0
    else:
    print("i am not hungry! ")

    class SongBird(Brid):
    def __init__(self):
    super(SongBird, self).__init__()
    self.sound = "ko ko"
    def sing(self):
    print(self.sound)

    sbird = SongBird()
    sbird.eat()
    sbird.eat()
    sbird.sing()

  • 相关阅读:
    ACM训练二B题
    ACM训练二A题
    hdu 1213 -how many tables
    hdu 4135 -Co-prime
    acm-青蛙的约会哦~
    HDU1711 【kmp算法 基础题】
    有向无环图(DAG)模型之-----嵌套矩阵(与猴子与香蕉很像)
    关于 C/C++左移右移运算符 的总结
    acm集训训练赛(二)D题【并查集】
    acm集训训练赛A题【签到题】
  • 原文地址:https://www.cnblogs.com/sysnap/p/3442188.html
Copyright © 2020-2023  润新知