叽叽喳喳,嘻嘻哈哈

导航

关于 私有变量的访问问题【 java python]

#coding:utf-8
class Teacher():
    __clas = ''  # 类私有变量同样遵循,只能在类内部访问,外部无法访问,但是类的方法可以访问同类所有对象私有变量这个规则。
    def __init__(self):
        __name = ""

    def get_name(self):
        return self.__name
    def equ(self,tac):
        return self.__name == tac.__name  # __name 是私有变量,规定是私有变量只能在类内部访问。但是,类内部的方法,可以访问该类的所有实例对象的私有变量。
                                        # 这种规则同样在java中使用

    def equa(self,stu):
        # print(self.__name == stu.__namee) # 这里会报错,因为 Student类中 __namee 是私有变量。只能在类内部访问。
        return self.__name == stu.get_name()  #所以采用过这种方式。

    def set_name(self,name):
        self.__name = name

    def set_stu_name(self,std): #
        std.set_name("liudaxia")


class Student():
    __age  = ''
    def __init__(self):
        __namee =""

    def get_name(self):
        return self.__namee
    def set_name(self,name):
        self.__namee = name




if __name__ == "__main__":
    s1 = Student()
    s1.set_name("zhanzhao")
    t1 = Teacher()
    t1.set_name("LI")
    print(t1.equa(s1)) # False
    t2 = Teacher()
    t2.set_name("LI")
    print(t1.equ(t2))  # true
    t1.set_stu_name(s1)
    print(s1.get_name())  # liudaxia


class A{
    private int a = 10;
    public void summ(A that){
        this.a += that.a; // 虽然 a是私有变量,但是因为 that也属于 A类,所以其私有变量可以被访问。
    }
    public void summ(B that){
//        this.a += that.b  // 访问 b 的私有变量将会出错 
        this.a += that.getB(); //采用这种方式访问私有变量
    }
}


class B{
    private int b = 20;
    public void mucc(B that){
        this.b *= that.b;
    }
    public int getB(){
        return this.b;
    }
}

posted on 2017-10-21 22:04  叽叽喳喳,嘻嘻哈哈  阅读(173)  评论(0编辑  收藏  举报