OOP编程,类的创建,封装,继承,多态,c++与python在语法上略有不同。
1.python类的创建,实例生成,删除
class person(object): #定义一个类, class是定义类的语法,Role是类名,(object)是新式类的写法
def __init__(self, name, age):#构造函数,在生成一个角色时要初始化的一些属性就填写在这里
self.name = name
self.age= age
def __del__(self): #析构函数
print("delete")
def fun1(self):
print("fun1...")
def fun2(self):
print("fun2...")
def print_gun(self, name):
print("just myname= %s" % name)
p1 = person('Alex', '12' ) #生成一个实例 , 会自动把参数传给person下面的__init__(...)方法
p2 = person('Jack', '13')
del p1
2.继承,多态:C++ 用public python 和JAVA都是super
2.1C++代码
基类:
#include <iostream>
using namespace std;
//基类People
class People
{
public:
People(char *name, int age);
virtual void display(); //声明为虚函数
protected:
char *m_name;
int m_age;
};
People::People(string name, int age):m_name(name), m_age(age) {} //默认构造函数
void People::display()
{
cout<<m_name<<"今年"<<m_age<<"岁了,是个无业游民。"<<endl;
}
派生类:
class Teacher: public People
//派生类Teacher 派生类是用Public关键词
class Teacher: public People
{
public:
Teacher(char *name, int age, int salary);//多了一个变量salary
virtual void display(); //声明为虚函数
private:
int m_salary;
};
Teacher::Teacher(string name, int age, int salary) : People(name, age), m_salary(salary) {}
void Teacher::display()
{
cout<<m_name<<"今年"<<m_age<<"岁了,是一名教师,每月有"<<m_salary<<"元的收入。"<<endl;
}
2.2python 代码
基类 父类
class Person(object):
members = 0 # 初始学校人数为0
def __init__(self, name, age):#1.构造函数
self.name = name
self.age = age
def tell(self): #
pass
def abstractFun(self): # 3.被继承函数,子类中会有不同实现 C++中叫虚函数
raise NotImplementedError("Subclass must implement abstract method")
def enroll(self):
Person.members += 1
print("\033[32;1mnew member [%s] is enrolled,now there are [%s] members.\033[0m " % (
self.name, Person.members))
def __del__(self): #2.析构函数
print("\033[31;1mmember [%s] is dead!\033[0m" % self.name)
派生类 子类
1.与C++比类,定义不用public 直接(),构造函数用super表示父类
2.与C++比,无virtual关键字
class Teacher(Person):
def __init__(self, name, age, salary):
super(Teacher, self).__init__(name, age) #构造函数 super关键字
self.salary = salary
self.enroll()
def teaching(self): #本类特有的函数
print("Teacher [%s] is teaching [%s] for class [%s]" % (self.name, self.course, 's12'))
def tell(self): #继承来的函数 无virtual关键字
msg = '''Hi, my name is [%s], works for [%s] as a [%s] teacher !''' % (self.name, 'Oldboy', self.course)
print(msg)
def abstractFun(self): # 子类实现多态的一个函数
print("teacher")
#派生类2
class Student(Person):
def __init__(self, name, age, grade, sid):
super(Student, self).__init__(name, age)
self.grade = grade
self.sid = sid
self.enroll()
def tell(self): #继承于父类,但子类自我实现
msg = '''Hi, my name is [%s], I'm studying [%s] in [%s]!''' % (self.name, self.grade, 'Oldboy')
print(msg)
def abstractFun(self):# 子类实现多态的一个函数
print("Student")