Python decorator method and decorator property All In One
Python decorator method and decorator property All In One
修饰器/装饰器;静态方法;实例方法; 属性方法;
- @classmethod decorator
- @staticmethod decorator
- @property decorator
# cls
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# 实例方法
def calculate_area(self):
return self.width * self.height
# 类方法 (类似 js 的 static method)
@classmethod
def new_square(cls, side_length):
return cls(side_length, side_length)
# 类方法
square = Rectangle.new_square(5)
print("类方法", square.calculate_area())
# 类实例方法
s = Rectangle(3, 3)
print("类实例方法", s.calculate_area())
"""
$ py3 ./classmethod-decorator.py
类方法 25
类实例方法 9
"""
# static
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
# 静态方法
@staticmethod
def validate_topping(topping):
if topping == "pineapple":
# raise ValueError("No pineapples!")
return False
else:
return True
ingredients = ["cheese", "onions", "spam"]
# all()
if all(Pizza.validate_topping(i) for i in ingredients):
pizza = Pizza(ingredients)
print("🍕pizza =", pizza)
bug = "pineapple"
print("🍍pineapple", Pizza.validate_topping(bug))
"""
$ py3 ./staticmethod-decorator.py
🍕pizza = <__main__.Pizza object at 0x10c527fa0>
🍍pineapple False
"""
@property decorator
# property
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
# 只读属性方法
@property
def pineapple_allowed(self):
return False
# 普通方法
def get_pineapple_flag(self, flag = False):
self._flag = flag
return flag
pizza = Pizza(["cheese", "tomato"])
# 直接读取属性,直接调用属性名称
print(pizza.toppings)
# 间接读取属性,直接调用方法名称 + 括号
print(pizza.get_pineapple_flag())
print(pizza.get_pineapple_flag(True))
print(pizza._flag)
# 只读属性,仅省略了一个方法调用的括号 💩
print("✅ 只读属性 ", pizza.pineapple_allowed)
# AttributeError: can't set attribute ❌
pizza.pineapple_allowed = True
# print(pizza.pineapple_allowed)
"""
$ py3 ./class-property-decorator.py
['cheese', 'tomato']
False
True
True
✅ 只读属性 False
Traceback (most recent call last):
File "/Users/xgqfrms-mm/Documents/github/Python-3.x-All-In-One/src/class-property-decorator.py", line 29, in <module>
pizza.pineapple_allowed = True
AttributeError: can't set attribute
"""
- property getter
- property setter
# setter/getter
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
self._pineapple_allowed = False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
# property setter
@pineapple_allowed.setter
def pineapple_allowed(self, value):
if value:
password = input("Enter the password: ")
if password == "123":
self._pineapple_allowed = value
else:
raise ValueError("Alert! Intruder!")
@pineapple_allowed.getter
def pineapple_allowed(self):
return "✅" + str(self._pineapple_allowed)
try:
pizza = Pizza(["cheese", "tomato"])
print(pizza.toppings)
print(pizza._pineapple_allowed)
print("\npizza.pineapple_allowed =", pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)
except ValueError:
print("ValueError")
finally:
print("finished")
"""
$ py3 ./class-property-setter-getter.py
['cheese', 'tomato']
False
pizza.pineapple_allowed = ✅False
Enter the password: 123
✅True
"""
demos
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
python all
function
all(iterable)
Return True
if all elements of the iterable are true
(or if the iterable is empty
).
Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
https://docs.python.org/3/library/functions.html#all
https://www.w3schools.com/python/ref_func_all.asp
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17585057.html
未经授权禁止转载,违者必究!