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

相關文章
相關標籤/搜索