jnrain / issue-tracker

*此处没有代码* 各种问题讨论交流区, 有话要说就开issue
4 stars 1 forks source link

求解惑:关于python的继承 #12

Closed xcodebuild closed 10 years ago

xcodebuild commented 10 years ago

下午在修改微信代码时碰到一个问题把自己吓了一跳,是我对python继承的理解一直不正确么,先看一段java代码

//A.java
public class A {
    public StringBuffer data;

    public A(){
        this.data = new StringBuffer();
    }

    public void set(String value){
        data.append(value);
    }
}

//B.java
public class B extends A {
    public void set_b(){
        this.set("This is set by class B");
    }
}

//C.java
public class C extends A {
    public void set_c(){
        this.set("This is set by class C");
    }
}

//Tester.java
public class Tester {

    public static void main(String[] args) {
        B b = new B();
        C c = new C();
        b.set_b();
        c.set_c();
        // TODO Auto-generated method stub
        System.out.println("B:" + b.data);
        System.out.println("C:" + c.data);
    }

}

输出结果很容易理解,是

B:This is set by class B
C:This is set by class C

但是同样的逻辑在Python中的结果似乎一点都不一样,下面时python代码

#coding:utf-8
class A:
    data = {}
    def _set(self,value,key):
        self.data[value] = key

class B(A):
    def set_b(self):
        self._set("b","this is b")

class C(A):
    def set_c(self):
        self._set("c","this is c")

if __name__ == '__main__':
    b = B()
    c = C()
    b.set_b()
    c.set_c()
    print b.data
    print c.data
    #甚至我们可以
    print B.data
    print C.data
    #以及
    print A.data
    print A().data

得到的结果全部是

{'c': 'this is c', 'b': 'this is b'}

为什么,b和c是两个子类的不同实例,为什么他们(甚至于A())都会共用data的数据,python这样的设计有什么原因或者优势么

xen0n commented 10 years ago
class A:
    data = {}
    def _set(self, value, key):
        self.data[value] = key

你没好好看Python教程, 这个data是class attribute啊... Python里实例属性是构造函数里初始化的, 像这样:

class A(object):
    def __init__(self):
        self.data = {}
    def _set(self, value, key):
        self.data[value] = key

这样作用域才一致... 还有请让你的所有类都直接或间接从object继承, 不要干写class Something:这样的代码, 具体原因你现在不用管. 如果感兴趣请自行Google "python old-style classes"

xcodebuild commented 10 years ago

原来这样,的确没认真看过教程什么的,一直按照其他语言的思路写- -,谢站长了,这个issue我关了