gpt4 book ai didi

python - 如果对象属性在范围之间,则类对象只能调用方法

转载 作者:行者123 更新时间:2023-12-04 09:50:35 25 4
gpt4 key购买 nike

我想让我的代码更复杂,这是我遇到的问题

class Person:

def __init__(self, age):
self.age = age

def drives(self):
if self.age >= 18:
# Do more things which driving entitles
print("you can drive")

def studies(self):
if self.age <= 25:
# Do more student stuffs
print("Good luck with your education")

bob = Person(14)
bob.drives()
bob.studies()

jim = Person(35)
jim.drives()
jim.studies()

我不喜欢一进入方法就检查,增加标记。我知道装饰师,他们是这里最好的选择吗?我将如何在这个用例中使用它们?我希望它看起来像:
class Person:

def __init__(self, age):
self.age = age

@check_if_person_age_is_greater_than_17
def drives(self):
# Do more things which driving entitles
print("you can drive")

@check_if_person_age_is_less_than_26
def studies(self):
# Do more student stuffs
print("Good luck with your education")

bob = Person(14)
bob.drives() # either this method cannot be accessed or returns nothing, since bob is 14
bob.studies() # this should work normally

jim = Person(35)
jim.drives() # this should work normally
jim.studies() # either this method cannot be accessed or returns nothing, since jim is 35

如果我的问题不简洁或不值得,我很抱歉。

最佳答案

所以这就是我能够想出的。这大大清理了代码,但可能使其有点难以理解。如果这是您的要求,您还可以将装饰器变成类方法或静态方法。

from functools import wraps


def prerequisite(age_limit=18, _func=None):
def _wrapper_function(func):
@wraps(func)
def _inner_function(*args, **kwargs):
if args[0].age >= age_limit:
return func(*args, **kwargs)
else:
raise ValueError("You can't {func_name} at the age of {age}".format(func_name=func.__name__, age=args[0].age))
return _inner_function
if _func is None:
return _wrapper_function
else:
return _wrapper_function(_func)

class Person(object):
def __init__(self, age):
self.age = age

@prerequisite(age_limit=16)
def drive(self):
# Do more drive stuffs
print("You are eligible to apply for a license to drive. Please drive responsibly.")

@prerequisite(age_limit=21)
def drink(self, drink_name):
# Do more drink stuffs
# Passing an argument just to show that arguments can also be passed like this.
print("You can legally drink. Alcohol is dangerous to health, drink cautiously. Your favorite drink is {drink_name}".format(drink_name=drink_name))

@prerequisite()
def fly(self):
# Do more fly stuffs
# This is an example for how default args for decorator works
print("You are eligible to apply for a license to fly.")

bob = Person(19)

bob.drive() # works
bob.fly() # works
bob.drink("Beer") # This will throw an exception

关于python - 如果对象属性在范围之间,则类对象只能调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62019832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com