作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想让我的代码更复杂,这是我遇到的问题
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/
有一条(相对)众所周知的 Perl 公理:“只有 Perl 可以解析 Perl”。我想知道 Perl 6 是否仍然如此? 扩大讨论...考虑到 PyPy 最近的更新,我想到了这个问题。 Perl 独特
这是设置。在上一个问题中,我发现我可以通过子组件中的状态传递对象属性,然后使用 componentDidUpdate 获取该对象属性。在这种情况下,状态和属性都称为到达。 这是基本代码... expo
我运行的是 10.5.2 社区版。我已经标记了 源/主要/资源 作为源目录。我可以右键单击并“编译”某些文件,据我所知,这意味着 IDE 将文件复制到与发送类文件的“com.mydomain.pack
我是一名优秀的程序员,十分优秀!