2014-12-28 73 views
1

如何在return_fee功能中使用todayreturntimePython,如何使用部分功能外功能

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 
+3

添加'self.today'和'self.returntime'爲'__init__'?然後你可以從'return_fee'調用'self.today'和'self.returntime'。如果你在'time_of_return'中定義它們(就像你現在所做的那樣),你只能在調用'time_of_return'後調用'return_fee'。 – Bjorn

+1

'return_fee()'方法的'Movie'參數有什麼意義? – glglgl

+2

此代碼不工作的原因是由於變量範圍,但也有一些風格不一致 - 如果return_fee旨在成爲Movie類的一個方法(它看起來像其他方法縮進),那麼我會建議將其'Movie'參數更改爲'self'(以避免名稱衝突),然後建議使用類實例的變量self.fee,self.today,self.returntime - 在從內部設置它們之後time_of_return方法。如果您不將'Movie'更改爲'self',則Movie.fee將引用靜態類變量而不是實例。 –

回答

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> 
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__()正在使用那類從outside.But參數,當您使用Movie類,你必須定義的參數。

1

如果你想time_of_returnreturn_fee是實例屬性,請從__init__time_of_return設置它們,然後用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可隨時間變化),呼叫從內部return_fee和功能time_of_return確保它返回的東西:

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將是更好的默認值。