【发布时间】:2017-12-16 00:02:40
【问题描述】:
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())
运行时,此代码打印:
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'
但是当我把 Dog 类中的 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)
它正确打印,说:
Spot 身高 53 厘米,体重 27 公斤,说 Ruff
这是为什么?
编辑:我刚刚意识到打印的是 Animal 的 toString 方法,而不是 Dog 的 toString 方法。
【问题讨论】:
-
为什么要将每个属性都设为私有?
-
我正在看一个 python 教程,教程中的那个人能够使它与私有属性一起工作。教程链接:youtube.com/…
-
这是一个糟糕的教程...检查 cmets。你不是唯一一个面临这个错误的人
-
我同意@pythad。该视频使用了糟糕的术语,教授了非常单一的 Python,并对课程的实际工作方式做出了错误的假设。我建议阅读Python documentation for a brief overview of classes,并观看更好的教程,例如this one。我没有看过所有系列,但作者将军似乎正确地教授了类和 OOP 概念。
标签: python class inheritance parent