简体   繁体   English

Python类和对象属性错误:对象没有属性

[英]Python Classes and Objects Attribute error : object has no attribute

I am new to python and while learning OOP in python i am getting errors like 我是python的新手,在python中学习OOP时遇到类似以下错误

AttributeError: 'Dog' object has no attribute 'sound'

for below code 对于下面的代码

class Dog:
    def __init__(self, name, age):
        self.name  = name
        self.age  = age

    def description(self):
        return print(f"name is {self.name} and age is {self.age}")

    def speak(self, sound):
        return print(f"{self.name} says {self.sound}")

tommy = Dog("tommy",10)
tommy.description()
tommy.speak("bow-bow")

Now my other doubt is related to inheritance where i am getting error like: 现在我的另一个疑问与继承有关,而我却遇到如下错误:

AttributeError: 'Bulldog' object has no attribute 'speed'

for below code : 对于以下代码:

class Dog:
    def __init__(self, name, age):
        self.name  = name
        self.age  = age

    def description(self):
        return print(f"name is {self.name} and age is {self.age}")


class Bulldog(Dog):
    def run(self, speed):
        return print(f"The speed of dog is {self.speed}")

tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)

I believe you need to remove the self. 我相信您需要去除自我。 when trying to return the print as these are passed through as parameters and not identified in the object itself. 尝试返回打印时,因为这些作为参数传递且在对象本身中未标识。

class Dog:
    def __init__(self, name, age):
        self.name  = name
        self.age  = age

    def description(self):
        return print("name is {self.age} and age is {self.age})


class Bulldog(Dog):
    def run(self, speed):
        return print(f"The speed of dog is {speed}")

tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)

This is the same for both speed and sound, note I also changed some formatting about how the print statement works 速度和声音都一样,请注意,我还更改了一些有关打印语句工作方式的格式

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM