我對python的使用不到一年的經驗還是比較新的,我一直通過在谷歌應用程序引擎上構建一個相當大的項目來學習它。它成長爲10k +代碼行和html模板的龐然大物,所以我正在重構相當大一部分代碼以遵循更加嚴格的MVC體系結構。在GAE中創建一個類方法「模板」Python
我的問題是直接關於python的問題。我不知道我想要創建什麼,所以我只想用一個例子。
這是用於顯示視圖我目前的「基本」代碼:
class MainHandler(webapp.RequestHandler):
def get(self):
tUser = users.get_current_user()
tContext = {
'user': tUser,
'login': users.create_login_url(self.request.uri),
'logout': users.create_logout_url(self.request.uri),
}
#User is logged in
if (tUser):
#code for loading view information and adding to the context dict
#CUSTOMIZATION GOES HERE
else:
self.redirect("/")
tmpl = os.path.join(os.path.dirname(__file__), 'logged-in.html')
self.response.out.write(render(tmpl, tContext))
我想借這個樣板代碼和抽象不知何故,也許有預謀的方式/追加了「可定製「每個類方法的代碼?
我想我可能會使用一個裝飾器來做到這一點,但我沒有python的導師之外的stackoverflow指向我在正確的方向。我寧願選擇最可能的pythonic方法,或者至少在這種情況下被認爲是「最佳實踐」。
python版本是2.7.2。
編輯
注意,如果我能做到這一點與裝飾,那麼有什麼必要對我來說,能夠從一個完全不同的類和python文件調用的設計師嗎?我希望能夠將我的裝飾器放在一個文件中並從別處引用它,所以我的代碼按照合理的規範化。 =)
編輯2
這是我在控制檯制定了測試代碼,我要離開的晚上或我會更加完善它。然而,看起來,這成功地訪問和修改了這個類的屬性,這幾乎是我認爲你需要在GAE中實現的。
class Decorators():
@staticmethod
def BeginInit(pInFunction):
def OutFunction1(self):
print str(self.innerv)
pInFunction(self)
return OutFunction1
@staticmethod
def EndInit(pInFunction):
def OutFunction2(self):
self.innerv = 5
pInFunction(self)
print "this is test 3"
return OutFunction2
class Test2Handler():
innerv = 10
@Decorators.BeginInit
@Decorators.EndInit
def TestPrint(self):
print self.innerv
print "this is test 2"
打印
10
5
this is test 2
this is test 3
有趣的是,是啊,這也將工作。 =) – 2012-01-11 15:52:37