【发布时间】:2020-09-13 02:52:31
【问题描述】:
我希望让我的代码更复杂,这就是我遇到的问题
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
如果我的问题不够简洁或不值得,我很抱歉。
【问题讨论】:
-
这只会让代码变得比它需要的更复杂
-
@rdas 是的。我想你是对的。我认为检查更好,因为它们使代码更具可读性
标签: python python-3.x oop object