[英]How to have Static and Method Functions with the same name
I'm trying to create a class for interacting with a MySQL Database.我正在尝试创建一个 class 来与 MySQL 数据库进行交互。 This class will connect to the database storing the connection object and cursor. Allowing for multiple actions without reconnecting every time.这个 class 将连接到存储连接 object 和 cursor 的数据库。允许执行多个操作而无需每次都重新连接。 Once you're done with it, the cursor and connection need to be closed.完成后,需要关闭 cursor 和连接。 So I've implemented it as a context manager and it works great.所以我将它实现为上下文管理器并且效果很好。
I need the support to be able to do multiple actions without reopening the connection each time, but most of the time I am only running one Query/command.我需要支持才能执行多项操作而无需每次都重新打开连接,但大多数时候我只运行一个查询/命令。 So I end up having to write the below code to run a single query.所以我最终不得不编写下面的代码来运行单个查询。
with MySQLConnector() as connector:
connector.RunQuery(QUERY)
I thought it would be nice to be able to run single line commands like this我认为能够像这样运行单行命令会很好
MySQLConnector().RunQuery(QUERY)
but this leaves the connection open.但这会使连接保持打开状态。
I then thought this implementation would allow me to do single and multiple actions all nicely context managed.然后我认为这个实现将允许我执行单个和多个操作,所有这些操作都很好地进行了上下文管理。
class MySQLConnector():
@staticmethod
def RunQuery(query):
with MySQLConnector() as connector:
connector.RunQuery(query)
def RunQuery(self, query):
self.cursor.execute(query)
self.connection.commit()
# Single Actions
MySQLConnector.RunQuery(QUERY)
# Mulitple Actions
with MySQLConnector() as connector:
connector.RunQuery(QUERY_1)
connector.RunQuery(QUERY_2)
However, the method function seems to override the static method and only one way will work at a time.但是,方法 function 似乎覆盖了 static 方法,一次只能使用一种方法。 I know I could just have two separately named functions but I was wondering if there was a better/more pythonic way to implement this?我知道我可以有两个单独命名的函数,但我想知道是否有更好/更 pythonic 的方法来实现它?
As this answer points out, you can use some __init__
trickery to redefine the method if it is being used as non-static (as __init__
will not run for static methods).正如这个答案所指出的,如果它被用作非静态方法,您可以使用一些__init__
技巧来重新定义该方法(因为__init__
不会运行 static 方法)。 Change the non-static RunQuery
to something like _instance_RunQuery
, then set self.RunQuery = self._instance_RunQuery
.将非静态RunQuery
更改为类似_instance_RunQuery
的内容,然后设置self.RunQuery = self._instance_RunQuery
。 Like this:像这样:
class A:
def __init__(self, val):
self.add = self._instance_add
self.val = val
@staticmethod
def add(a, b):
obj = A(a)
return obj.add(b)
def _instance_add(self, b):
return self.val + b
ten = A(10)
print(ten.add(5))
print(A.add(10, 5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.