024_类方法的装饰

1,propertypython

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

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,伪属性的  查看 修改 删除spa

 

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
# 静态方法      有默认的参数 就象函数同样blog

相关文章
相关标签/搜索