我在调用方法时遇到问题的主题类:
#.tools - where definded get_current_time, generate_id
#db is object of class and have method excute_query, wich send query to
from .tools import *
class topic:
def __init__(self,theme,author,about,db):
self.time_of_creation = get_current_time
self.theme = theme
self.author = author
self.about = about
self.sb_id = generate_id()
self.db = db
try:
#inserting data into DB
self.db.excute_query(f"""INSERT INTO user VALUES ("{get_current_time()}, '{self.theme}',
'{self.author}','{self.about}',
'{generate_id()}')""")
return 1
except Exception as e:
print(str(e))
return [0, str(e)]
@staticmethod
def all(self):
return self.db.excute_query("SELECT * FROM topic")
我正在尝试调用 all() 方法:
topic.all()
作为响应,我得到 AttributeError: 'function' object has no attribute 'all'。我怎样才能解决这个问题?
在我看来,类方法 (
@classmethod) 可能适合这种情况:第一个选项是使用独立函数而不是静态方法。为了那个原因
删除该行
直接应用参数,而不是参数
self(您只需要确定要使用哪个数据库)db请注意,
all我使用的是 name而不是 nameall_,因为......all是标准 Python 函数的名称。删除此函数定义之前的缩进 - 您不希望它与您的 class 关联
topic,并相应地缩进下一个命令。好吧,在这个命令中,删除该部分self.并topic使用您的表的名称 - 从您的代码中我猜测它是user:然后您可以将此函数称为
all_(имя_датабазы).第二个选项是修复静态方法。为此,请丢弃它
self,因为 静态方法对对象或类一无所知。方法,代替
使用
然后您可以将此方法称为
topic.all_(имя_датабазы)。