首页 > 编程语言 > 详细

Python之面向对象

时间:2019-05-25 10:33:37      阅读:109      评论:0      收藏:0      [点我收藏+]

类与对象

class Father(object):
    def __init__(self, name, age):
        self.__privateFatherAge = age;
        self.publicFatherName = name;
    #定义共有属性和私有属性!
    __privateFatherAge = 44;
    publicFatherName = 'feige';
    #私有方法访问共有属性
    def __privateMethod(self):
        print('the name of father is:'+self.publicFatherName);
    #共有方法访问私有属性!
    def publicMethod(self):
        print('the age of father is :'+str(self.__privateFatherAge));

f = Father('fei', 24);
print(f.publicFatherName);
#print(f.__privateAge);出错
print(f._Father__privateFatherAge);
f.publicMethod();
#f.__privateMethod();出错
f._Father__privateMethod();
#f2 = Father();出错

结果

fei
24
the age of father is :24
the name of father is:fei

总结

Phyton在编译的时候动了手脚,所以访问私有属性或者私有方法会报错,你要你按照特殊的形式,就可以访问私用属性或者私有方法了。
Python目前的私有机制是虚伪私有,Python的类是没有权限控制的,所有的变量都是可以被外部访问的。

继承

Python之面向对象

原文:https://www.cnblogs.com/feiqiangsheng/p/10921287.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!