我正在读代码.有一个类__del__定义了哪个方法.我发现这个方法用于销毁类的实例.但是,我找不到使用此方法的地方.主要原因是我不知道如何使用这种方法,可能不是这样:obj1.del().那么,我的问题是如何调用该__del__方法?感谢您的任何帮助.
我正在制作一个Python项目,我必须从数据库中搜索和检索数据.
我尝试创建一个类,在其中我声明了连接并进行了查询,这里到目前为止我没有更多.
import MySQLdb
dbc =("localhost","root","1234","users")
class sql:
db = MySQLdb.connect(dbc[0],dbc[1],dbc[2],dbc[3])
cursor = db.cursor()
def query(self,sql):
sql.cursor.execute(sql)
return sql.cursor.fetchone()
def rows(self):
return sql.cursor.rowcount
sqlI = sql()
print(sqlI.query("SELECT `current_points` FROM `users` WHERE `nick` = 'username';"))
Run Code Online (Sandbox Code Playgroud)
因此,主要问题是变量db并且cursor不能从同一个类的其他def /函数调用.我想得到的是一个很好的查询,我可以在那里查询并检索它的内容.这将总结我的代码,因此我应该这样做.
有没有一种 Pythonic 的方式来自动自动__exit__处理一个类的所有成员?
class C:
def __init__(self):
self.a = open('foo')
self.b = open('bar')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
# Is it correct to just forward the parameters here?
self.a.__exit__(self, exc_type, exc_value, traceback)
self.b.__exit__(self, exc_type, exc_value, traceback)
Run Code Online (Sandbox Code Playgroud)
我能做到这一点,而无需手动调用__exit__上a和b?我什至__exit__正确调用吗?
假设我拥有的资源file不像示例中那样,并且没有像closeor那样的方法destroy。在__enter__and之上实现这样的方法可能是一种好习惯__exit__吗?
该__enter__方法的返回值不应该self始终是。
Python文档说:
object.__enter__(self)输入与此对象相关的运行时上下文。with语句会将此方法的返回值绑定到该语句的as子句中指定的目标(如果有)。
这样做,为了做任何实际的事情,不self应该总是从__enter__类的方法中返回它,否则,就不能从上下文中调用其他类方法。
例如,在下面的代码中,s.main()可以正常工作,但b1.main()会出错。
class a(object):
def __init__(self):
pass
def __enter__(self):
return self
def __exit__(self ,type, value, traceback):
return self
def main(self):
print " in a::main self %d " , id(self)
class b(object):
def __init__(self):
pass
def __enter__(self):
return "something else"
def __exit__(self ,type, value, traceback):
pass
def main(self):
print "in b::main !! self id " , id(self)
with a() as s:
s.main()
with b() as b1:
b1.main()
s …Run Code Online (Sandbox Code Playgroud) 所以,我无法加载我的 json 文件,我不知道为什么,谁能解释我做错了什么?
async def give(msg, arg):
if arg[0] == prefix + "dailycase":
with open("commands/databases/cases.json", "r") as d:
data = json.load(d)
Run Code Online (Sandbox Code Playgroud)
由于某种原因,我收到此错误:
with open("commands/databases/cases.json", "r") as d:
AttributeError: __enter__
Run Code Online (Sandbox Code Playgroud) 我想知道,使用 with 语句和 psyopcg2 关闭与 Postgres 数据库的连接的正确方法是什么。
import pandas as pd
import psycopg2
def create_df_from_postgres(params: dict,
columns: str,
tablename: str,
) -> pd.DataFrame:
with psycopg2.connect(**params) as conn:
data_sql = pd.read_sql_query(
"SELECT " + columns + ", SUM(total)"
" AS total FROM " + str(tablename),
con=conn
)
# i need to close conection here:
# conn.close()
# or here:
conn.close()
return data_sql
Run Code Online (Sandbox Code Playgroud)
这是处理连接的更好方法吗?
def get_ci_method_and_date(params: dict,
columns: str,
tablename: str,
) -> pd.DataFrame:
try:
connection = psycopg2.connect(**params)
data_sql = pd.read_sql_query('SELECT ' …Run Code Online (Sandbox Code Playgroud) 我的目标是解压缩.tar.gz文件,而不是导致文件的子目录.
我的代码基于这个问题,除了解压缩.zip我正在解.tar.gz压缩文件.
我问这个问题,因为我得到的错误非常模糊,并且没有在我的代码中发现问题:
import os
import shutil
import tarfile
with tarfile.open('RTLog_20150425T152948.gz', 'r:gz') as tar:
for member in tar.getmembers():
filename = os.path.basename(member.name)
if not filename:
continue
# copy file (taken from zipfile's extract)
source = member
target = open(os.path.join(os.getcwd(), filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我复制了链接问题中的代码并尝试将其更改为处理.tar.gz成员而不是.zip成员.运行代码后,我收到以下错误:
Traceback (most recent call last):
File "C:\Users\dzhao\Desktop\123456\444444\blah.py", line 27, in <module>
with source, target:
AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)
从我已经完成的阅读中,shutil.copyfileobj将两个"类似文件"的对象作为输入.member是一个TarInfo对象.我不确定TarInfo对象是否是类文件对象所以我尝试更改此行:
source …Run Code Online (Sandbox Code Playgroud) 我使用SQLAlchemy(非常好的ORM,但文档不够清楚)与PostgreSQL通讯
一切都很好,直到出现一种情况,即达到最大连接限制的postgres“崩溃”原因:不再允许连接(max_client_conn)。
这种情况使我认为我做错了。经过几次实验后,我弄清楚了如何不再面对该问题,但是还剩下一些问题。
下面,您将看到没有提到问题的代码示例(在Python 3+中,PostgreSQL设置为默认设置),以及我想听听的内容最终是下列问题的答案:
连接到数据库:
from sqlalchemy.pool import NullPool # does not work without NullPool, why?
def connect(user, password, db, host='localhost', port=5432):
"""Returns a connection and a metadata object"""
url = 'postgresql://{}:{}@{}:{}/{}'.format(user, password, host, port, db)
temp_con = sqlalchemy.create_engine(url, client_encoding='utf8', poolclass=NullPool)
temp_meta = sqlalchemy.MetaData(bind=temp_con, reflect=True)
return temp_con, temp_meta
Run Code Online (Sandbox Code Playgroud)
获取会话以使用DB的功能:
from contextlib import contextmanager
@contextmanager
def session_scope():
con_loc, meta_loc = connect(db_user, db_pass, db_instance, 'localhost') …Run Code Online (Sandbox Code Playgroud) 我有很多这样的代码块:
try:
a = get_a()
try:
b = get_b()
# varying codes here, where a and b are used
finally:
if b:
cleanup(b)
finally:
if a:
cleanup(a)
Run Code Online (Sandbox Code Playgroud)
我希望写一些像这样的魔术代码:
some_magic:
# varying codes here, where a and b are also available
Run Code Online (Sandbox Code Playgroud)
这可能吗?
python ×9
python-3.x ×3
enter ×1
json ×1
mysql-python ×1
oop ×1
pandas ×1
postgresql ×1
psycopg2 ×1
sqlalchemy ×1
tar ×1