python - 无法调用类 bark()

标签 python class

我是 python 新手,我编写了以下代码。

我不明白为什么我不能从对象调用 bark() 类 并打印出来。我正在使用 eclipse pydev

请帮忙!!

class DOG():
    def __init__(self,mybreed):
        self.breed = mybreed
        def bark(self):
            print("WOOF {}".format(mybreed))

my_dog = DOG(mybreed="Goat")

print(my_dog.breed)
my_dog.breed = 'WOLF'
print(my_dog.breed)

print(my_dog.bark())

最佳答案

问题是缩进,您已在 __init__ 中定义了 brak,请将类定义更改为:

class DOG():
    def __init__(self, mybreed):
        self.breed = mybreed

    def bark(self):
        print("WOOF {}".format(self.breed))

In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to.

有用链接:Here

感谢@nixon,也感谢您应该使用self访问实例属性,请仔细查看format(self.breed)

关于python - 无法调用类 bark(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53630250/

相关文章:

jquery - 禁用 jquery 中的元素

python - 在函数中导入导入 - Python 2.6

python - Keras + Tensorflow模型优化: TypeError: clone_model() got an unexpected keyword argument 'clone_function'

class - Dart 扩展 Map 以方便延迟加载

java - 类必须声明为抽象或实现抽象方法错误

class - Haskell 声明 Show 类的实例

php - Python:PHP "=="的等价物是什么

python - 时间序列分类

UDP 比特流跟踪器的 Python 抓取

python - 无法将对象附加到实例变量(列表)