如何在today
功能中使用returntime
和return_fee
?
import datetime
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
答案 0 :(得分:1)
如果您希望time_of_return
和return_fee
成为实例属性,请从time_of_return
拨打__init__
进行设置,然后使用self
作为前缀:
class Movie(object):
def __init__(self,title):
self.title = title
self.time_of_return()
def time_of_return(self):
self.today = datetime.datetime.now()
self.returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = None
delta = self.today - self.returntime
# ... presumably do something else
或者(因为,特别是,today
可能会随时间而变化),请从time_of_return
内调用函数return_fee
,并确保它返回一些内容:
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
return today, returntime
def return_fee(Movie):
fee = None
today, returntime = self.time_of_return()
delta = today - returntime
# ... presumably do something else
顺便说一句,将代码缩进4个空格是一个好主意。 None
(或0)对fee
来说是更好的默认值。
答案 1 :(得分:1)
我会这样做:
class Movie(object):
def __init__(self,title):
self.title = title
def get_times(self):
now = datetime.datetime.now()
return now, now + datetime.timedelta(days=30)
def time_of_return(self):
now, returntime = self.get_times()
return returntime
def return_fee(self):
fee = -2
now, returntime = self.get_times()
delta = now - returntime
return <whatever based on fee and delta>
答案 2 :(得分:0)
class Movie(object):
def __init__(self,title,today,returntime):#<----
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
那是因为__init__()
正在从外部使用for class的参数。但是,当你使用Movie类时,你必须定义那些参数。