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方法。
你爲什麼要做每個屬性私人? – pythad
我正在看一個python教程,教程中的人能夠使它與私有屬性一起工作。鏈接到教程:https://www.youtube.com/watch?v=N4mEzFDjqtA&feature=youtu.be&t=32m4s – Danin2
這是一個錯誤的教程...檢查評論。你不是唯一面對這個bug的人 – pythad