xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python OOP & Class private method All In One

Python OOP & Class private method All In One

Python Class private method

demos

  1. 代码缩进错误

缩进错误

  1. 调用私有方法错误

image

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
    #def _call(self):
        #print("%s 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
    def _call(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
    def __private_call(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))


s = student('ken',10,60,3)
s.speak()
print("\n")
s._call()
print("\n")
s.__private_call()

"""
  File "script.py", line 32
    def __private_call(self):
                            ^
TabError: inconsistent use of tabs and spaces in indentation

Exited with error status 1

"""

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

REPL

https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3

refs

https://www.runoob.com/python3/python3-class.html

python 私有方法

Python 默认的成员方法和成员属性都是公开的,没有类似 Java 的 public、private、protected 等关键词来修饰;
在 Python 中定义私有成员只需要在变量名函数名前加上 "__"两个下划线,那么这个函数或变量就变成私有的了;
方法也是一样,方法名前面加了2个下划线的话表示该方法是私有的,否则为公有的;

https://www.cnblogs.com/dy99/p/14785848.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-05-11 19:57  xgqfrms  阅读(4)  评论(1编辑  收藏  举报