Python中的继承和init方法 [英] Inheritance and init method in Python

查看:146
本文介绍了Python中的继承和init方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的初学者。我无法理解继承和 __ init __()

I'm begginer of python. I can't understand inheritance and __init__().

class Num:
    def __init__(self,num):
        self.n1 = num

class Num2(Num):
    def show(self):
        print self.n1

mynumber = Num2(8)
mynumber.show()

结果: 8

这没关系。但我将 Num2 替换为

This is OK. But I replace Num2 with

class Num2(Num):
    def __init__(self,num):
        self.n2 = num*2
    def show(self):
        print self.n1,self.n2

结果:错误。 Num2没有属性n1。

在这种情况下, Num2 怎么样?访问 n1

In this case, how can Num2 access n1?

推荐答案

在第一种情况下, Num2 正在扩展类 Num ,因为您没有重新定义名为 __ init __() Num2 中,它继承自 Num

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.


当一个类定义 __ init __()
方法时,类实例化
会自动调用 __ init __() for
新创建的类实例。

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

在第二个情况,因为你在 Num2 中重新定义 __ init __(),你需要显式调用超类中的那个( Num )如果你想扩展它的行为。

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

这篇关于Python中的继承和init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆