简体   繁体   English

当我在PyCharm中运行此程序时,出现以下错误

[英]When I run this program in PyCharm I get the following errors

When I run this code. 当我运行这段代码时。 I get the following errors 我收到以下错误

Traceback (most recent call last): File "C:/Users/Nabeel Hussain Syed/PycharmProjects/Hello World/check.py", line 80, in print(spot.toString()) File "C:/Users/Nabeel Hussain Syed/PycharmProjects/Hello World/check.py", line 66, in toString return "{} is {} cm tall and {} kilograms and say {}. His owner is {}".format(self.__name, AttributeError: 'Dog' object has no attribute '_Dog__name' 追溯(最近一次通话):文件“ C:/ Users / Nabeel Hussain Syed / PycharmProjects / Hello World / check.py”,行80,在print(spot.toString())中,文件“ C:/ Users / Nabeel Hussain Syed / PycharmProjects / Hello World / check.py“,第66行,在toString中返回“ {}高{}厘米,{}公斤,说{}。他的所有者是{}”。format(self .__ name,AttributeError: “狗”对象没有属性“ _Dog__name”

Open the link of the image to check out the errors. 打开图像的链接以检查错误。

    class Animal:
    __name = None
    __height = 0
    __weight = 0
    __sound = 0

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

    def set_name(self, name):
        self.__name = name

    def set_height(self, height):
        self.__height = height

    def set_weight(self, weight):
        self.__weight = weight

    def set_sound(self, sound):
        self.__sound = sound

    def get_name(self):
        return self.__name

    def get_height(self):
        return str(self.__height)

    def get_weight(self):
        return str(self.__weight)

    def get_sound(self):
        return self.__sound

    def get_type(self):
        print("Animal")

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

cat = Animal('Whiskers', 33, 10, 'Meow')
print(cat.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 set_owner(self, owner):
        self.__owner = owner

    def get_owner(self):
        return self.__owner

    def get_type(self):
        print("Dog")

    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)


    def multiple_sounds(self, how_many=None):
        if how_many is None:
            print(self.get_sound())
        else:
            print(self.get_sound() * how_many)

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

Attributes with names starting with double underscores are considered "private", and not accessible from child classes. 名称以双下划线开头的属性被视为“私有”,并且不能从子类访问。 You could still access them by names like _Animal__name ( Animal is a parent class name in which attribute was defined), but it's a bad practice. 您仍然可以使用_Animal__name类的名称来访问它们( Animal是在其中定义属性的父类名称),但这是一种不好的做法。

More information in official documentation: https://docs.python.org/3.6/tutorial/classes.html#private-variables 官方文档中的更多信息: https : //docs.python.org/3.6/tutorial/classes.html#private-variables

the double-underscore has significance in Python. 双下划线在Python中具有重要意义。 Please see this excerpt from a previous stack overflow answer : 请从以前的堆栈溢出答案中查看此摘录:

Double leading underscore 双领先下划线

This one actually has syntactical significance. 这实际上具有语法意义。 Referring to self.__var1 from within the scope of your class invokes name mangling. 在类范围内引用self .__ var1会调用名称修饰。 From outside your class, the variable will appear to be at self._YourClassName__var1 instead of self.__var1. 从您的类外部,该变量将显示为self._YourClassName__var1而不是self .__ var1。 Not everyone uses this - we don't at all where I work - and for simple classes it feels like a slightly absurd and irritating alternative to using a single leading underscore. 并不是每个人都使用此功能-我们根本不在我的工作地点-对于简单的课程,使用单个下划线就显得有些荒谬和令人讨厌。

However, there is a justification for it existing; 但是,存在理由。 if you're using lots of inheritance, if you only use single leading underscores then you don't have a way of indicating to somebody reading your code the difference between 'private' and 'protected' variables - ones that aren't even meant to be accessed by subclasses, and ones that subclasses may access but that the outside world may not. 如果您使用大量继承,如果仅使用单个前导下划线,则您将无法指示某人阅读您的代码,即“私有”变量与“受保护”变量之间的区别-甚至不意味着由子类访问,子类可以访问但外部世界不能访问。 Using a single trailing underscore to mean 'protected' and a double underscore to mean 'private' may therefore be a useful convention in this situation (and the name mangling will allow a subclasses to use a variable with the same name in their subclass without causing a collision). 因此,在这种情况下,使用单个尾部下划线表示“受保护”,使用双下划线表示“私有”可能是一个有用的约定(名称改写将允许子类在其子类中使用具有相同名称的变量,而不会引起碰撞)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试在Pycharm中运行或调试我的代码时,我只会遇到错误 - When I try to run or debug my code in Pycharm I only get errors 为什么我在 pycharm 和 IDLE 中运行相同的程序会得到不同的结果? - Why do I get different results when I run the same program in pycharm and IDLE? 程序在IDE(Pycharm)上运行时可以运行,但在终端上运行时却不能运行? - Program works when I run it on the IDE (Pycharm) but not when I run it on the terminal? 运行此程序时出现 FileNotFoundError - I get a FileNotFoundError when I run this Program 如何在终端中运行 python 程序并让它显示错误? - How do I run a python program in terminal and get it to display errors? 当我在 pycharm 中运行 ascii 艺术程序时,什么都不做 - doesn't do anythinng when I run the ascii art program in pycharm 运行插值函数的代码时出现错误 - I get errors when I run my code for the interpolation function 我怎样才能让我的 python 程序运行得更快? 我收到以下代码的“killed 9”消息 - How can i make my python program run faster? I get "killed 9" message with following code 为什么我在运行此程序时会收到 Terminator 错误? - Why do I get a Terminator error when I run this program? 为什么在尝试使用Anaconda环境在PyCharm中加载matplotlib时会出现错误列表? - Why do I get a list of errors when trying to load matplotlib in PyCharm with the Anaconda environment?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM