python類相關

#python雜記,寫一寫,以後忘了,方便回來看吧
#一:類的繼承

與C++中繼承不同,python中使用括號包括基類

C++:

class  base_class    /*父類*/
{
    private:
        
    public:
        
    protected:
}

class sub_class:inherit_way  base_class   /*inherit_way繼承方式*/
{
    
}

python:

class  base_class:
    def  __init__(self,name="",age=0):#初始化類時自動執行
        self.__name=name  #帶有__私有
        self.age=age  #age非私有
    def  __fun():#定義私有方法
        ......
class  inherit(base_class):#繼承對象放在括號裏面
    def __init__(self,name,age):
        base_class.__init__(self,name,age)#繼承中,構造函數不會自動調用,要手動執行
        #上面init可以用下面的super代替
        #super(inherit,self).__init__(name,age)#super爲內置函數
        #如果在派生類中找不到方法,纔會去基類裏找
        

python中如果要強制訪問私有屬性,可以通過類下:

class base:
	def __init__(self,name,age):
		self.__name=name
		self.age=age
#以下爲測試
>>> test=base("shui",10)
>>> print(test.age)
10
>>> print(test.__name)#錯誤
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print(test.__name)
AttributeError: 'base' object has no attribute '__name'
>>> print(test._base__name)#
shui
>>> 

 

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