第十章第1讲:python之构造方法与super函数

1. 构造方法的简单应用

    注意:包含有构造方法的类,在实例化的时候一定要同时给参数赋值,否则会报错

# Demo1 构造方法
class Person():
    def __init__(self,name):
        self.name = name
    def greet(self):
        print("Hello,I'm %s" % self.name)
p = Person("Bela")
print(p.greet())

 

# Demo2 构造方法,多个参数
class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def greet(self):
        print("Hello,I'm %s,%d years old." % (self.name,self.age))
p = Person("Bela",14)
print(p.name)
print(p.age)
print(p.greet())

 

2.重写一般方法与特殊方法

# 首先设计一个简单的子类,子类通过pass(代码桩)
# Demo3 继承
class A():
    def __init__(self):
        self.name = 42
    def hello(self):
        print("I'm A")
class B(A):
    pass
foo = B()
print(foo.hello())
print(foo.name)

结果:
I'm A
None
42

 

# Demo4 B类中定义自己的方法
# B类与A类有同样的方法,子类B重写父类的方法
class A():
    def __init__(self):
        self.name = 42
    def hello(self):
        print("I'm A")
class B(A):
    def hello(self):
        print("I am B")
foo = B()
print(foo.hello())
print(foo.name)

结果:
I am B
None
42

 

3. 重写构造方法

# 重写构造方法
# 如果子类里面重写了init方法
# 在对子类(Cat)实例化后,再cat,name的时候会报错
# 原因:Cat类重写了父类Animal的init方法
class Animal():
    def __init__(self,name):
        self.name = name
    def speak(self):
        print("都会叫")
class Cat(Animal):
    def __init__(self,weight):
        self.weight = weight
cat = Cat(10)
print(cat.weight)
print(cat.speak())
# 如下代码会报错
print(cat.name)

 

# 如果子类init方法用到了父类init方法中的属性
# 考虑继承
class Animal():
    def __init__(self,name):
        self.name = name
    def speak(self):
        print("都会叫")
class Cat(Animal):
    def __init__(self,name,weight):
        Animal.__init__(self,name)
        self.weight = weight
cat = Cat("CC",10)
print(cat.name)
print(cat.weight)
print(cat.speak())

4.super函数

# super 函数
class Bird():
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print("Aoaoao")
            self.hungry = False
        else:
            print("No,thanks")
class songBird(Bird):
    def __init__(self):
        super().__init__()
        self.sound = "Balabala"
    def sing(self):
         print(self.sound)
a = songBird()
print(a.sing())
print(a.eat())

 

posted @ 2019-07-27 13:32  Ling_07  阅读(179)  评论(0编辑  收藏  举报