类中属性的私有化:
在类中属性前加上双下滑线就是私有化的属性了,不能在类外直接通过类名调用
class Dog:
__role = 'dog'
d = Dog()
print(Dog.__role)
报错!
我们可以用__dict__看看Dog中有那些属性看看__role变成了什么
class Dog:
__role = 'dog'
print(Dog.__dict__)
{'__module__': '__main__', '_Dog__role': 'dog', '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
我们可以看到__role属性变成了_Dog__role
当我们用_Dog__role调用看看
class Dog:
__role = 'dog'
print(Dog._Dog__role)
dog
我们可以看到role可以被调用了。所以在python中绝对的私有化是没有的我们总能想到方法调用。
python中的私有化我感觉可以这么理解当你的在变量名前添加了双下划线就等于把变量名改为了 _当前类名__属性名
property
装饰器
可以将类中的方法伪装成一个属性
用法如下
from math import pi
class Cricle:
def __init__(self, r):
self.r = r
def perimeter(self):
return 2 * pi * self.r
def sqare(self):
return pi * self.r ** 2
在上述的代码中我们定义了一个圆类我们可以实例化一个圆,每次我们想要得到其周长和面积是我们都可以调用他们的方法,但是我们可以这么认为面积和周长是圆的固有属性而不是方法,我们怎么样可以跟调用属性一样调用方法呢,python还是厉害.有个property的装饰器可以用到
from math import pi
class Cricle:
def __init__(self, r):
self.r = r
@property
def perimeter(self):
return 2 * pi * self.r
@property
def sqare(self):
return pi * self.r ** 2
现在我们可以直接跟调用属性一样调用方法了
c1 = Cricle(5)
print(c1.perimeter)
输出:
31.41592653589793
property和私有化属性的组合使用
class Goods:
__discount = 0.8
def __init__(self, name, price)
self.name = name
self.__price = price
@property
def price(self):
return self.__price * __discount
@price.setter
def price(self, new_price):
self.__price = new_price
@price.deleter
def price(self):
print('删除了')
apple = Goods(5)
print(apple.price)
apple.price = 8
print(apple.price)
del apple.price
输出结果:
4.0
6.4
删除了!
NB!
类中的静态和类方法
class Goods:
__discount = 0.8
@classmethod
def modify_discount(cls, new_discount):
Goods.__discount = new_discount
类方法的调用不需要实例化直接用类名调用,cls代表的是Goods类和self差不多都代表本身。
什么时候用类方法:当需要使用类中的静态方法,且不需要和对象相关的任何操作时
静态方法和普通方法没什么大的区别
class A:
@staticmethod
def func(args): # 静态方法
print('123')
A.func(args)
可以通过类名直接带调用。