多态、封装

# 广义上的封装
# class 类名:
# def 方法名(self):pass
# 是为了只有这个类的对象才胡使用定义在类中的方法

# 狭义上的封装: 把一个名字藏在类中

class Goods:
__discount = 0.2 # 私有的静态变量
print(__discount) # 0.2

# 在类的外部不能引用私有的静态变量
# 类中的静态变量和方法名,在程序加载 的过程 中,已经执行完了,不需要等待调用
# 在这个类加载完成 之前,Goods这个类名,还没见有出现在全局名称空间中
# 私有的静态变量可以在类的内部使用,用来隐藏某个变量的值。

print(Goods.__dict__) # {'__module__': '__main__', '_Goods__discount': 0.2, '__dict__': <attri

class Goods:
__discount = 0.7 # 私有的静态变量
# 变形: _类名__私有变量

# print(Goods.__discount) # AttributeError: type object 'Goods' has no attribute '__discount' 类对象没有这个属性
print(Goods._Goods__discount) # 这样可以从类的外部访问,但是从编程规范的角度上出发,不建议在类的外部
# 使用私有的静态变量


class Student:
def __init__(self,name,age):
self.__name = name # 对象的私有变量,类外部,不能操作
self.age = age
def getName(self):
return self.__name
student = Student("王小宝",28)
# print(student.__name) # 报错,对象没有这个属性
print(student.getName()) # 王小宝 这是通过类中的方法,来操作对象的私有变量
print(student.__dict__) # {'_Student__name': '王小宝', 'age': 28} 对象的属性,是存在对象的名称空间中的,并且对于
# 对象的私有变量,也作了一个变形,以对象所属的直接类 _类名__私有变量

print(student.age)
student.age = "aaaa" # python是弱类型 语言
print(student.age)

class Goods:
__discount = 0.6 # 私有的静态变量
def __init__(self,name,price):
self.name = name
self.__price = price # 我不想让你看到这个值
def getPrice(self):
return self.__price * self.__discount
def changePrice(self,newPrice): # 我想让你修改一个值的时候有一些限制
if type(newPrice) is int:
self.__price = newPrice
else:
print("本次价格修改不成功")
pear = Goods("pear",89)
print(pear.getPrice()) # 53.4
pear.changePrice(100) # 将价格改为100
print(pear.getPrice()) # 60.0

class User:
def __init__(self,username,password):
self.username = username
self.__pwd = password
self.pwd = self.__getpwd()
def __getpwd(self):
return hash(self.__pwd)
user = User("chirs",'jiayong')
print(user.pwd) # -4615835297725458545

# 类中的私有成员
# 私有的静态变量
# 私有的对象变量
# 私有的方法
# 私有的变量,在内存中存储时 会 变形,在使用时,也会变形
# 为什么要定义一 个私有变量呢?
# 不想让你看到这个变量
# 不想让你修改这个变量
# 想让你修改这个变量有一些限制
# 有些方法或属性不希望被子类继承
#

# 广义上的封装,把属性和函数都放到类里
# 狭义上的封装,定义 私有成员

# 私有变量能不能 在类的外部 定义 ????
class A:
__private = 1000
print(__private)
def getAge(self):
print(self.__age)
print(A.__dict__) # {'__module__': '__main__', '_A__private': 1000, '__dict__': <attrib
print(A._A__private) # 1000
A.__language = "chinese"
print(A.__dict__)
A._A__age = 18 # 通过 这种方式,可以在外部定义一个私有的静态属性
print(A.__dict__)
print(A._A__age) # 18
A.getAge(A) # 18

# 私有变量能不能被继承???
class A:
age = 100
__country = "china"
def __init__(self,name):
self.__name = name # 存储时 变形 _A__name
class B(A):
# print(age) # NameError: name 'age' is not defined
# print(__country)
def getName(self):
return self.__name # _B__name

b = B("jeason")
print(b.__dict__)
# b.getName() # AttributeError: 'B' object has no attribute '_B__name'

# 结论: 对于 类中的私有变量 ,在那个类中,变量时,就是那个类的名字 和 下划线打头 : _类名__私有变量
原文地址:https://www.cnblogs.com/chris-jia/p/9557751.html