56.C#和python类继承中的构造函数问题

一、C#类继承中的构造函数

public class Animal:Creature
{
    public Animal():this("马")//注意:这里是实际参数,不是对参数的定义。
    {
        Console.WriteLine("这是Animal类");
    }

    public Animal(string str):base(str)
    {
        Console.WriteLine($"这是带参数的Animal类。参数是{str}");
    }
}

public class Creature
{
    public Creature()
    {
        Console.WriteLine("这是Creature类");
    }
    public Creature(string str)
    {
        Console.WriteLine($"这是带参数的Creature类,参数是{str}");
    }
}
static void Main(string[] args)
{
    //第一步,调用Creature()
    //第二步,调用Animal("马")
    //第三步,调用Animal()函数体里的代码

    Animal ani = new Animal();
    //第一步,调动Creature("驴")
    //第二步,调用Animal("驴")
    Animal ani2 = new Animal("驴");

}

输出是:

二、python类继承中的构造函数

class Creatrue:
    def __int__(self):
        print("这是Creature类")
    # 以下不是构造函数
    # def Creature(self):
    #     print("这是Creature类")
    # def Creatrue(self,str):
    #     print("这是带参数的Creature类,参数是"+str)

class Animal(Creatrue):
    def __init__(self):
        print("这是Animal类")

class Animal_1(Creatrue):
    def __init__(self):
        Creatrue.__int__(self)
        print("这是Animal_1类")

class Animal_2(Creatrue):
    def __init__(self):
        super(Animal_2, self).__init__()
        print("这是Anima1_2类")
#注意:重写_init__不会自动调用基类的__init__。
#要调用必须明确地写出代码。
ani=Animal()
ani1=Animal_1()
ani2=Animal_2()

输出是:

三、C#和Python此处语法的不同

1.构造函数方法不同

C#中要用类名()作为构造函数,python中用__init__专有函数作为构造函数。

2.对基类构造函数调用不同

在c#中调用继承类构造函数时,会强制调用基类构造函数。python则不调用基类构造函数,除非在继承类构造函数中明确调用基类构造函数。两个各有利弊。前者省事,后者自由。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章