#!/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