python的繼承

私有變量

除了在對象內部(包括其子類)不能訪問的“私有”實例變量在Python中不存在。但是,大多數Python代碼遵循一個約定:以下劃線(例如_spam爲前綴的名稱應被視爲API的非公開部分(無論它是函數,方法還是數據成員)。它應被視爲實施細節,如有更改,恕不另行通知。

只能通過本類的非私有方法訪問。

#-*- coding:UTF-8 -*-
class parent:
    count=100;
    __privateName="zhansan";
    def __init__(self):
        print ("fu init");
        self.age=10;
        self.num="12234";
        self.name="fu";
    def setName(self,name):
        print ("fulei setName");
        self.name=name;
    def getName(self):
        print ("fulei getName");
        return self.name;
    def getPrivateName(self):
        return self.__privateName;
class child(parent):
    def __init__(self):
        parent.__init__(self);
        print ("zilei init");

    def setName(self,name):
        parent.setName(self,name);
        print ("zilei setName");
    def getName(self):
        print ("zilei getName");
        return parent.getName(self);
    def getPrivateName(self):
        return parent.getPrivateName(self);

a=child();
print (a.getName());
print a.count;
print a.getPrivateName();

wKioL1jAwRyhpKL6AAAotfNkK24920.png-wh_50

初始化類時,先進入子類__init__()方法,調用父類的__init__()構造方法,再

執行子類__init__()代碼,完成初始化。

有同名函數時,子類對象調用子類函數。

子類沒有調用的函數時,子類對象調用父類函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章