Python之特性,静态方法与类方法

# 特性(property)--类中方法伪装成属性

# 定义一个圆
# from math import pi
# class Circle:
#     def __init__(self,r):
#         self.__r = r
#     @property
#     def perimeter(self):
#         return self.__r * pi * 2
#     @property
#     def area(self):
#         return self.__r **2 * pi
# c1 = Circle(2)
# print(c1.perimeter) # 让方法像属性一样调用
# print(c1.area)

# 属性的查看删除与修改
# 定义一个商品
# class Goods:
#     __discount = 0.5  # 折扣比例
#     def __init__(self,name,price):
#         self.name = name
#         self.__price = price
#     @property
#     def price(self): # 查看价格(通过折扣计算)
#         return self.__price * Goods.__discount
#     @price.setter
#     def price(self,price): # 修改价格,只能传一个参数(之后的赋值操作时传入的值)
#         self.__price = price
#     @price.deleter
#     def price(self): # 删除价格
#         del self.__price
# pork = Goods("钱大妈猪肉",12)
# print(pork.price) # 查看价格(像属性一样查看值)
# pork.price = 14 # 像属性一样修改值
# print(pork.price)
# del pork.price # 像属性一样删除
# print(pork.price) # AttributeError: 'Goods' object has no attribute '_Goods__price'

# classmethod--类方法
class Goods:
    __discount = 0.5  # 折扣比例
    def __init__(self,name,price):
        self.name = name
        self.__price = price
    @property
    def price(self): # 查看价格(通过折扣计算)
        return self.__price * Goods.__discount
    @price.setter
    def price(self,price): # 修改价格,只能传一个参数(之后的赋值操作时传入的值)
        self.__price = price
    @price.deleter
    def price(self): # 删除价格
        del self.__price
    @classmethod
    def changeDiscount(cls,newDiscount): # 当方法不依赖于对象时,则定义为类方法,也可以理解为方法只涉及静态方法时
        cls.__discount = newDiscount
apple = Goods("苹果",7)
print(apple.price)
Goods.changeDiscount(0.8)
print(apple.price)
# staticmethod--静态方法 -- 如果一个函数既不依赖于对象,也不依赖于类,则定义成静态方法
class A:
    @staticmethod
    def func():
        print("this is a static function")
A.func()
# 静态方法与类方法均推荐使用类名调用,但是对象名也可以调用,普通方法默认传self,类方法默认传入cls,静态方法没有默认传入的参数

猜你喜欢

转载自blog.csdn.net/qq_40199698/article/details/88833157