简体   繁体   English

类继承(Python)输出问题

[英]Class Inheritence (Python) Output Problems

I'm going through 'Learning Python The Hard Way', and I got to the class lesson. 我正在经历'学习Python艰难之路',我上课了。 I understood it (or I at least think I did!) and tried to create a simple variation, using my own names, functions, etc... 我理解它(或者我至少认为我做过!)并尝试使用我自己的名字,功能等创建一个简单的变体......

Now the problem I'm having is that the code won't return anything in command line\\powershell. 现在我遇到的问题是代码不会在命令行\\ powershell中返回任何内容。 It doesn't have any errors, it just goes to another line of input. 它没有任何错误,只是转到另一行输入。

Here's the Code: 这是代码:

class Animal(object):
    '''represents any animal'''
    def __init__(self, legs, size):
        self.legs = legs
        self.size = size

    def detail_animal(self):
        '''show # of legs and size'''
        print "Name: %r\nAge: %r" % (self.legs, self.size)

class canine(Animal):   
    '''represents a canine'''

    def __init__(self, legs, size, hair_length):
        Animal.__init__(self, legs, size)
        self.hair_length = hair_length

    def detail_canine(self):
        Animal.detail(self)
        print 'Has %r inch long hairs.' % self.hair_length

class feral_cat(Animal):
    '''represents a feral cat'''

    def __init__(self, legs, size, tail_length):
        Animal.__init__(self, legs, size)
        self.tail_length = tail_length

    def detail_feral(self):
        Animal.detail(self)
        print "Tail Length: %r" % tail_length

c1 = canine(4, 2, 0.5)
c2 = canine(5, 3, 0.75)
fc1 = feral_cat(4, 5, 3)
a = Animal(4, 2)

Thanks in advance! 提前致谢!

There are a few problems in your code: the Animal class doesn't have a method called detail , which you try to call in all its subclasses. 您的代码中存在一些问题: Animal类没有名为detail的方法,您尝试在其所有子类中调用该方法。 You should probably rename detail_animal(self) to detail(self) . 您应该将detail_animal(self)重命名为detail(self) To have your program print some output add these lines at the end: 要让程序打印一些输出,请在最后添加这些行:

c1.detail_canine()
c2.detail_canine()
fc1.detail_feral()
a.detail()

Furthermore if your program is meant to experiment with method overriding, ie the possibility of redefining base class methods in subclasses, you should try and change detail_canine(self) and detail_feral(self) into detail(self) . 此外,如果您的程序是要尝试方法重写,即在子类中重新定义基类方法的可能性,您应该尝试将detail_canine(self)detail_feral(self)更改为detail(self) Remember to make the change also in the lines I suggested you should add! 请记住在我建议您添加的行中进行更改! You'll see that when you instantiate (ie create) an object of the base class Animal 's detail(self) method gets called; 当你实例化(即创建)基类的对象时,你会看到Animaldetail(self)方法被调用; when you instantiate one of the subclasses that class's detail(self) method gets called instead. 当您实例化其中一个子类时,将调用类的detail(self)方法。

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

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