x公有属性
class Animal:
x = 10
def test(self):
print(Animal.x)
print(self.x)
pass
class Dog(Animal):
def test2(self):
print(Dog.x)
print(self.x)
pass
# 测试代码
a = Animal()
# a.test()
b = Dog()
# b.test2()
# print(Animal.x)
# print(Dog.x)
# print(a.x)
# print(b.x)
a = 666
# import 私有化属性
#
# print(私有化属性.a)
from 私有化属性 import *
print(a)
_x受保护属性
# class Animal:
# _x = 10
# def test(self):
# print(Animal._x)
# print(self._x)
# pass
#
# class Dog(Animal):
# def test2(self):
# print(Dog._x)
# print(self._x)
# pass
# 测试代码
# a = Animal()
# a.test()
# b = Dog()
# b.test2()
# print(Animal._x)
# print(Dog._x)
# print(a._x)
# print(b._x)
__all__ = ["_a"]
_a = 666
# import 私有化属性
#
# print(私有化属性._a)
from 私有化属性 import *
print(_a) # NameError: name '_a' is not defined
_xx 私有属性
class Animal:
__x = 10
def test(self):
print(Animal.__x)
print(self.__x)
pass
#
class Dog(Animal):
def test2(self):
print(Dog.__x)
print(self.__x)
pass
# 测试代码
a = Animal()
# a.test()
b = Dog()
# b.test2() #AttributeError: type object 'Dog' has no attribute '_Dog__x'
# print(Animal.__x) #AttributeError: type object 'Animal' has no attribute '__x'
# print(Dog.__x) #
# print(a.__x) #
# print(b.__x) #
#
__all__ = ["__a"]
__a = 666
import 私有化属性
print(私有化属性.__a)
from 私有化属性 import *
print(__a) # NameError: name '_a' is not defined
应用场景
class Person():
# 主要作用,当我们创建好一个实例对象后,会自动调用这个方法,来初始化这个对象
def __init__(self):
self.age = 18
def setAge(self, value):
if isinstance(value, int) and 0 < value < 200:
self.__age = value
else:
print("你输入额数据有问题,请重新输入")
def getAge(self):
return self.__age
p1 = Person()
p1.setAge(200)
# print(p1.getAge())
# p2 = Person()
# p2.age