Python的多继承最好是当C#或者Java里面的接口使用,这样结构不会混乱( 特殊情况除外)
来个例子:
class Animal(object):
pass
class Flyable(object):
"""飞的方法"""
pass
class Runable(object):
"""跑的方法"""
pass
class Dog(Animal, Runable):
pass
class Cat(Animal, Runable):
pass
class Bird(Animal, Flyable):
pass
class Dack(Animal, Runable, Flyable):
"""鸭子会飞也会跑"""
pass
和C#一样,Python的 父类构造函数不会被继承
其实从资源角度也不应该被继承,如果有1w个子类,那每个子类里面都有一个父类方法,想想这是多么浪费的一件事情?
2.3.C#继承 ¶
下课后,小明认真思考总结,然后对照Python写下了C#版的继承:
定义一个人类
public class Person
{
public string Name { get; set; }
public ushort Age { get; set; }
public Person(string name, ushort age)
{
this.Name = name;
this.Age = age;
}
public void Hi()//People
{
Console.WriteLine("Name: " + this.Name + " Age: " + this.Age);
}
public virtual void Show()//People
{
Console.WriteLine("Name: " + this.Name + " Age: " + this.Age);
}
}
定义一个学生类
public class Student : Person
{
#region 属性
/// <summary>
/// 学校
/// </summary>
public string School { get; set; }
/// <summary>
/// 班级
/// </summary>
public string StrClass { get; set; }
/// <summary>
/// 学号
/// </summary>
public string StrNum { get; set; }
#endregion
#region 构造函数
/// <summary>
/// 调用父类构造函数
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public Student(string name, ushort age) : base(name, age)
{
}
public Student(string name, ushort age, string school, string strClass, string strNum) : this(name, age)
{
this.School = school;
this.StrClass = strClass;
this.StrNum = strNum;
}
#endregion
/// <summary>
/// new-隐藏
/// </summary>
public new void Hi()//Student
{
Console.WriteLine("Name: " + this.Name + " Age: " + this.Age + " School: " + this.School + " strClass: " + this.StrClass + " strNum: " + this.StrNum);
}
/// <summary>
/// override-覆盖
/// </summary>
public override void Show()//Student
{
Console.WriteLine("Name: " + this.Name + " Age: " + this.Age + " School: " + this.School + " strClass: " + this.StrClass + " strNum: " + this.StrNum);
}
}
调用一下:
Person p = new Student("app", 10, "北京大学", "001", "01001");
p.Hi(); p.Show();
Console.WriteLine();
Student s = p as Student;
s.Hi(); s.Show();
结果:
Name: app Age: 10
Name: app Age: 10 School: 北京大学 strClass: 001 strNum: 01001
Name: app Age: 10 School: 北京大学 strClass: 001 strNum: 01001
Name: app Age: 10 School: 北京大学 strClass: 001 strNum: 01001
2.4C#接口的多实现 ¶
定义两个接口:
public interface IRun
{
//什么都不用加
void Run();
}
public interface IEat
{
void Eat();
}
定义一个Dog类来实现两个接口,这样dog就有了run和eat的方法了
var dog = new Dog();
dog.Eat();
dog.Run();
结果:
狗狗吃
狗狗跑
3 多态 ¶
3.1.Python ¶
说多态之前说说类型判断,以前我们用 type() or isinstance()
判断一个变量和另一个变量是否是同一个类型==> type(a)==type(b)
判断一个变量是否是某个类型==> type(a)==A or isinstance(a,A)