Python OOP & Class private method All In One
Python OOP & Class private method All In One
Python Class private method
demos
- 代码
缩进错误

- 调用
私有方法错误

#!/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个下划线的话表示该方法是私有的,否则为公有的;
©xgqfrms 2012-2021
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
未经授权禁止转载,违者必究!