024_类方法的装饰

1,property

  #内置装饰器函数 只在面向对象中使用,将类中的方法伪装成属性。
  #可以不添加这些,装饰成属性是为了代码规范,在属性设置里虽然可以计算,但不应该在属性设置里操作,操作应定义方法。因此需要计算的属性应该定义一个方法,而为了让伪属性(通过方法计算的属性)象属性所以用装饰器伪装成属性。
  #通过装饰器伪装成的属性,可以通过“对象.伪属性名”查看,但是,不能通过“对象.伪属性名 = 新值”方式改变伪属性值。

from math import pi
class Circle:
    def __init__(self,r):
        self.r = r
    @property	#通过装饰器将perimeter伪装成属性,但是该方法不能传入任何参数,只能是执行。
    def perimeter(self ):
        return 2*pi*self.r
    @property
    def area(self):
        return self.r**2*pi

c1 = Circle(5)
print(c1.area)     # 圆的面积  #该方法已经被装饰器伪装成属性,通过属性的方式调用。
print(c1.perimeter) # 圆的周长
#c1.perimeter = 8  #报错

2,伪属性与私有属性搭配,实现对外隐藏操作前的属性。外部只能查看到操作后的该属性。  

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
apple = Goods('苹果',5)
print(apple.price)

3,伪属性的  查看 修改 删除

class Person:
	def __init__(self,name):
		self.__name = name
		self.price = 20

	@property		#伪装属性(get方法)
	def name(self):
		return self.__name

	@name.deleter	#可以通过外部“del brother2.name”删除这个私有属性。
	def name(self):
		del self.__name

	@name.setter	#伪装属性不能修改,但定义这样的函数,就可以在外部可通过“brother2.name = 'newName'”方法修改。
	def name(self,new_name):
		self.__name = new_name

brother2 = Person('二哥')
del brother2.price
brother2.name = 'newName'
# del brother2.name
print(brother2.name)
# 只有定义了 property 才有get,set,del

4,

  # method 方法
  # staticmathod  静态的方法
  # classmethod   类方法  
 
  4.1,当这个方法的操作只涉及静态属性的时候 就应该使用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)
print(apple.price)
  4.2,# 在完全面向对象的程序中,
    # 如果一个函数 既和对象没有关系 也和类没有关系 那么就用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()

5,

# 类方法和静态方法 都是类调用的
# 对象可以调用类方法和静态方法么?   可以   一般情况下 推荐用类名调用
# 类方法          有一个默认参数 cls 代表这个类  cls
# 静态方法      有默认的参数 就象函数一样

 

原文地址:https://www.cnblogs.com/eternity-twinkle/p/10607818.html