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

"""

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 @   xgqfrms  阅读(6)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2022-05-11 SwiftUI App Sticker All in One
2022-05-11 Swift conditional statement All In One
2022-05-11 Chrome console.clear All In One
2022-05-11 Swift Function argument All In One
2021-05-11 CSS @property All In One
2021-05-11 但行好事,莫问前程 All In One
2020-05-11 React Hooks & React Context vs Redux All In One
点击右上角即可分享
微信分享提示