我一直在阅读和学习装饰器及其在python中的使用。我想我会尝试为我一直在研究的python脚本创建一个装饰器。根据我的阅读,我知道应该有很多方法可以用我所拥有的特定代码来完成这项工作。
到目前为止:
#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
import sqlite3
## create the Decorator class ##
class Deco:
## initialize function and pass in the function as an argument ##
def __init__(self,func):
self.func = func
## use the built in __call__ method to run when the decorator is called ##
## I having issues knowing what the proper to pass the function in as an argument ##
def __call__(self,func):
## right here I going to call the Vocab().dictionary() method ##
self.func
## I can have the Vocab method run after I don't have a preference ##
## this decorator is going to find the number of tables and entries in the ##
## database with every call ##
conn = sqlite3.connect('/home/User/vocab_database/vocab.db')
with conn:
cur = conn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
total = cur.fetchall()
print "You have %d tables " % len(total)
cur.execute("SELECT * FROM %s" % (total[0][0],))
ent = cur.fetchall()
print "You have %d entries" % len(ent)
class Vocab:
def __init__(self):
self.word = sys.argv[1]
self.def_count = 1
self.query = {}
@Deco
def dictionary(self,word):
br = mechanize.Browser()
response = br.open('http://www.dictionary.reference.com')
br.select_form(nr=0)
br.form['q'] = word
br.submit()
definition = BeautifulSoup(br.response().read())
trans = definition.findAll('td',{'class':'td3n2'})
fin = [i.text for i in trans]
for i in fin:
self.query[fin.index(i)] = i
self.create_database()
self.word_database()
return self.query
def create_database(self):
con = sqlite3.connect('/home/oberon/vocab_database/vocab.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Words(vocab_id INTEGER PRIMARY KEY, vocab TEXT)")
cur.execute("CREATE TABLE IF NOT EXISTS Definitions(def_id INTEGER, def TEXT, def_word INTEGER, FOREIGN KEY(def_word) REFERENCES Words(vocab_id))")
def word_database(self):
con = sqlite3.connect('/home/User/vocab_database/vocab.db')
with con:
spot = con.cursor()
spot.execute("SELECT * FROM Words")
rows = spot.fetchall()
spot.execute("INSERT INTO Words VALUES(?,?)", (len(rows),self.word))
spot = con.cursor()
spot.execute("SELECT * FROM Definitions")
rows_two = spot.fetchall()
for row in rows_two:
self.def_count += 1
for q in self.query:
spot.execute("INSERT INTO Definitions VALUES(?,?,?)", (self.def_count,self.query[q],len(rows)))
self.def_count += 1
print Vocab().dictionary(sys.argv[1])
运行此代码后,Deco
打印出来,运行并完成装饰器方法中的所有内容,但Vocab().dictionary()
打印出None
:
You have 2 tables
You have 4 entries
None
我确信这里的错误不仅仅是让Vocab().dictionary()
方法运行。如果有人可以帮助解决阻止这种情况正常工作的问题,那么一般情况下,我应该用装饰品更好地研究其他任何东西!
答案 0 :(得分:3)
self.func
没有调用函数,正如您所期望的那样(从评论中判断)。要调用它,您需要执行self.func()
。此外,如果要包装函数以便将值返回到外部,则需要执行return self.func()
,或者存储值并稍后返回(在with
块之后)。
但是,您的代码在其他方面似乎有点怀疑。例如,你有__call__
接受func
作为参数,但它没有被使用,而装饰者认为包装的dictionary
方法接受一个名为word
的参数,这显然是应该是一个字符串。这让我觉得你误解了装饰者是如何工作的。
当您使用@Deco
作为装饰器时,该类将作为参数传递给装饰。 Deco
实例本身就是结果,因此在此Vocab.dictionary
之后是Deco
的实例。当您再调用Vocab().dictionary()
时,您正在调用__call__
的{{1}}方法。因此,如果你试图包裹Deco
,你的Deco dictionary
应该接受__call__
接受的相同论点,并且应该将它们传递给dictionary
。 (这可能就是你遇到dictionary
错误的原因---你在没有参数的情况下调用self.func()
,但它需要一个参数。)