2017-07-11 43 views
3
import random 
import sys 
import os 
class Animal: 
    __name = "" 
    __height = 0 
    __weight = 0 
    __sound = "" 

    def __init__(self, name, height, weight, sound): 
     self.__name = name 
     self.__height = height 
     self.__weight = weight 
     self.__sound = sound 

    def toString(self): 
     return "{} is {} cm tall and {} kilograms and say {}".format(self.__name, 
                    self.__height, 
                    self.__weight, 
                    self.__sound) 

class Dog(Animal): 
    __owner = "" 
    def __init__(self, name, height, weight, sound, owner): 
     self.__owner = owner 
     super(Dog, self).__init__(name, height, weight, sound) 

    def toString(self): 
     return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name, 
                         self.__height, 
                         self.__weight, 
                         self.__sound, 
                         self.__owner) 

spot = Dog("Spot", 53, 27, "Ruff", "Derek") 
print(spot.toString()) 

當跑,這段代碼打印:Python的 - 從子類中的方法訪問父屬性是怪異

return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name, 
AttributeError: 'Dog' object has no attribute '_Dog__name' 

但是,當我把toString方法在狗類的一側多,像這樣:

class Dog(Animal): 
    __owner = "" 
    def __init__(self, name, height, weight, sound, owner): 
     self.__owner = owner 
     super(Dog, self).__init__(name, height, weight, sound) 

     def toString(self): 
      return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name, 
                         self.__height, 
                         self.__weight, 
                         self.__sound, 
                         self.__owner) 

它打印出正確的,他說:

點爲53釐米高和27公斤,說拉夫

這是爲什麼?

編輯:我只是意識到打印的東西是Animal的toString方法,而不是Dog的toString方法。

+0

你爲什麼要做每個屬性私人? – pythad

+0

我正在看一個python教程,教程中的人能夠使它與私有屬性一起工作。鏈接到教程:https://www.youtube.com/watch?v=N4mEzFDjqtA&feature=youtu.be&t=32m4s – Danin2

+0

這是一個錯誤的教程...檢查評論。你不是唯一面對這個bug的人 – pythad

回答

3

別類的默認值,或爲「宣言」的屬性,除非你瞭解不使用__ -prefixed名字爲什麼您可能需要使用這樣的名稱。另外,您不需要toString; __str__服務於相同的目的,並根據需要自動調用。

class Animal: 
    def __init__(self, name, height, weight, sound): 
     self.name = name 
     self.height = height 
     self.weight = weight 
     self.sound = sound 

    def __str__(self): 
     return "{} is {} cm tall and {} kilograms and say {}".format(self.name, 
                    self.height, 
                    self.weight, 
                    self.sound) 

class Dog(Animal): 
    def __init__(self, name, height, weight, sound, owner): 
     super(Dog, self).__init__(name, height, weight, sound) 
     self.owner = owner 


    def __str__(self): 
     s = super(Dog, self).__str__() 
     return "{} His owner is {}".format(s, self.owner) 

spot = Dog("Spot", 53, 27, "Ruff", "Derek") 
2

私有屬性就是這樣......私有。 Python中沒有保護變量的概念。通過用雙下劃線限制變量,可以防止甚至子類訪問它們。