Python 类的重写

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2017/11/7 22:46
# @Author : lijunjiang
# @File   : class2.py

"""
类的重写

在子类中,使用与父类中相同变量或方法名,可以重新定义父类中的属性和方法

"""
class A():
    def hello(self):
        print('Hello, i am A')
class B(A):
    pass
a = A()
b = B()
a.hello()
b.hello()
# 执行结果:
# Hello, i am A
# Hello, i am A
# 上例中可以看出class B 继承 class A 后具有了A 的方法hello()

# 重写 hello 方法

class C(A):
    def hello(self):     # 重写hello()方法
        print('Hello, I am class C')
c = C()
c.hello()
# 执行结果:Hello, I am class C
# 当在class C 中 重新定义与父类 class A 同名的方法hellp() 后,class C 的实例将不再调用class A 中定义的hello()方法而调用
# 自身定义的hello() 方法
# 即, 子类定义父类同名函数之后,父类函数被覆盖

# 重定__init__方法

class Person():
    def __init__(self):
        self.name = 'Person'
        # print('Tist is a class Person')

class Man(Person):
    def __init__(self):
        self.sex = 'M'
        # print('I am class Man, my name is {0}'.format(name))

# person = Person()
# print(person.name)
# man = Man()
# print(man.name)
# print(man.sex)
# 执行结果:
#   File "D:/Python/class/class2.py", line 54, in <module>
# Person
#     print(man.name)
# AttributeError: Man instance has no attribute 'name'

# 执行报错:子类Man 重写__init__构造函数后,没有从父类Person中继承其name属性
# 构造函数__init__,是每个类的默认方法,如上例在子类中重写了__init__方法后,其默认方法被重写,导致父类中的默认方法
#        无法被调用,失去其构造函数的作用
# 此时,如果在子类中重写__init__方法,且继承父类中的属性和方法时,可以使用方法 super()
# super(className, self).functionName([没有self] argv )


class Person():
    def __init__(self):
        self.name = 'Person'
        # print('Tist is a class Person')

class Gril(Person):
    def __init__(self):
        super(Gril, self).__init__()
        self.sex = 'nvhai'
        print('Class name is {0}'.format(self.sex))

gril = Gril()
print(gril.name)

# 执行结果:
#  File "D:/Python/class/class2.py", line 80, in <module>
#     gril = Gril()
#   File "D:/Python/class/class2.py", line 76, in __init__
#     super(Gril, self).__init__()
# TypeError: super() argument 1 must be type, not classobj

# 原因:定义父类的时候,一定要写继承object类,不然那就会有如下的报错信息:TypeError: super() argument 1 must be type, not classobj,增加parent(object)就可以轻松解决。

class Person(object):  # 执行时需注释上面已声明过的Person类和Man 类
    def __init__(self):
        self.name = 'Person'
        # print('Tist is a class Person')

class Gril(Person):
    def __init__(self):
        super(Gril, self).__init__()
        self.sex = 'nvhai'
        print('Class name is {0}'.format(self.sex))

gril = Gril()
print(gril.name)
# 执行结果:
# Class name is nvhai
# Person
# 使用super(className,self).functionName(没有self!!)的重点是不需要提供父类,这意味着如果改变了类继承关系,只需要改变一行代码(class C(P)),此时寻找基类的事由super函数完成
# 但其继承的类中必须有一个继承超级类 object


posted @ 2017-11-08 09:23  考鸡蛋  阅读(5328)  评论(0编辑  收藏  举报