简体   繁体   English

很简单; 初级班

[英]Very simple; beginner class

New to python and currently learning about classes and OOP. python的新手,目前正在学习类和OOP。 I'm trying to get the following simple piece of code to run but can't figure out why I'm getting an error. 我正在尝试运行以下简单代码,但无法弄清楚为什么会出错。 Please see code below: 请参见下面的代码:

class Animal(object):
    fur = True
    def real_animal(self):
        if fur:
            print "Real animal"
        else:
            print "Fake animal"

class Dog(Animal):
    fur = True
    def __init__(self, name): 
        self.name = name

rover = Dog("Rover")
rover.real_animal()

I get an error stating fur is not defined. 我收到一条错误消息,指出未定义毛发。 From my understanding, classes can inherit from classes. 据我了解,类可以从类继承。 So, since Rover is-a instance of class Dog, which is a class Animal. 因此,由于漫游者是-Dog类的实例,而Dog是Animal类。 Shouldn't I be able to run functions of base class Animal on Rover? 我是否应该能够在Rover上运行基类Animal的功能? I basically want to state dogs have fur and therefore are real animals. 我基本上想声明狗有毛皮,因此是真实的动物。

Thanks all for helping a newbie. 谢谢大家对新手的帮助。

You have at least two mistakes: 您至少有两个错误:

  • You need to refer to the fur variable as self.fur , because it's not a local variable but a variable on the instance / class 您需要将fur变量称为self.fur ,因为它不是局部变量,而是实例/类上的变量

  • In the Dog class, you call the variable has_fur , but in the parent class it's called just fur . Dog类中,您将变量has_fur ,但在父类中,它仅称为fur

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

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