python的繼承

私有變量

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

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

#-*- 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__()代碼,完成初始化。spa

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

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

相關文章
相關標籤/搜索