静态方法staticmethod、类方法classmethod、属性方法property
property
查看操作:把一个类方法伪装成一个类属性
from math import pi
class Circle:
def __init__(self,r):
self.r = r
@property
def perimeter(self):
return 2*pi*self.r
@property
def area(self):
return self.r**2*pi
c1 = Circle(5)
print(c1.area) #原本是c1.area()
print(c1.perimeter) #原本是c2.perimeter()
修改操作:
class Person:
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self,new_name):
self.__name = new_name
aaa = Person('aaa')
print(aaa.name)
aaa.name = 'bbb'
print(aaa.name)
删除操作:
class Person:
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
@name.deleter
def name(self):
del self.__name
leo = Person('leo')
del leo.name
print(leo.name) #会报错,因为名字已经被删了
#AttributeError: 'Person' object has no attribute '_Person__name'
classmethod
当这个方法的操作只涉及静态属性的时候 就应该使用classmethod来装饰这个方法
class Goods:
__discount = 0.8
def __init__(self,name,price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.__discount
@classmethod # 把一个方法 变成一个类中的方法,这个方法就直接可以被类调用,不需要依托任何对象
def change_discount(cls,new_discount):
cls.__discount = new_discount
apple = Goods('苹果',5)
print(apple.price)
Goods.change_discount(0.5) # Goods.change_discount(Goods)
print(apple.price)
'''
4.0
2.5
'''
staticmethod
在完全面向对象的程序中,如果一个函数,既和对象没有关系,也和类没有关系 那么就用staticmethod将这个函数变成一个静态方法
class Login:
def __init__(self,name,password):
self.name = name
self.pwd = password
def login(self):pass
@staticmethod
def get_usr_pwd(): # 静态方法
usr = input('用户名 :')
pwd = input('密码 :')
Login(usr,pwd)
Login.get_usr_pwd()