python vs C++ 类

1. 什么是动态语言(wikipedia)

在运行时,可以进行一些操作(静态语言在编译时执行),比如扩展对象的定义、修改类型等

2. 定义类和创建对象

C++ python
 1 class A{
 2 public:
 3     A(){ 
 4         cout << "A 构造函数"; 
 5         a = "a";
 6         common = "common_a";
 7     }
 8 //private:
 9     string a;
10     string common;
11 };
12 A a = A();
13 A* a_pointer = new A();
 1 class A():
 2     def __init__(self):
 3          print("init 函数")
 4          self.a = 'a'
 5          self.common = 'common_a'
 6 a = A()
 7 
 8 # 在执行时动态地修改对象,创建属性
 9 class ADynamic:
10     def __init__(self):
11         print("ADynamicinit 函数")
12 
13 adynamic = ADynamic()
14 adynamic.a = 'a'
15 adynamic.common = 'common_a'

3. 属性的访问限制

  C++ python
公有

public:

  int a;

self.a=1
保护

protected:

  int a;

self._a=1

//可通过obj._a访问

私有

private:

  int a;

self.__a=1

//可通过obj._类名__a访问

4. 多继承

C++ python
class AParentParent{
public:
    AParentParent(){
        cout << "AParentParent 构造函数" << endl;
        this->common = "common_aparentparent";
    }
    string common;
};

class AParent1 : AParentParent{
public:
    AParent1(){
        cout << "AParent1 构造函数" << endl;
        this->common = "common_aparent1";
    }
    string common;
};
class AParent2 : AParentParent{
public:
    AParent2(){
        cout << "AParent2 构造函数"<<endl;
        this->common = "common_aparent2";
    }
    string common;
};

class A : AParent1, AParent2{
public:
    A(){ 
        cout << "A 构造函数" << endl;
        a = "a";
        common = "common_a";
    }
//private:
    string a;
    string common;
};
A a = A();
// 输出内容
/*
AParentParent构造函数
AParent1构造函数
AParentParent构造函数
AParent2构造函数
A构造函数
*/
 1 class AParentParent:
 2     def __init__(self):
 3         print("AParentParent init 函数")
 4         self.common = "common_aparentparent"
 5 
 6 
 7 class AParent1(AParentParent):
 8     def __init__(self):
 9         super(AParent1, self).__init__()
10         print("AParent1 init 函数")
11         self.common = "common_aparent1"
12 
13 
14 class AParent2(AParentParent):
15     def __init__(self):
16         super(AParent2, self).__init__()
17         print("AParent2 init 函数")
18         self.common = "common_aparent2"
19 
20 
21 class A(AParent1, AParent2):
22     def __init__(self):
23         super(A, self).__init__()
24         print("A init 函数")
25         self.a = 'a'
26         self.common = 'common_a'
27 
28 ## 输出
29 # AParentParent init 函数
30 # AParent2 init 函数
31 # AParent1 init 函数
32 # A init 函数
33 ##

 

//待续...

//static,类方法,__slots__,多态...

posted @ 2018-09-09 13:06  huapyuan  阅读(600)  评论(0编辑  收藏  举报