Python: 定义不初始化的对象变量
Python: define object variable without initialization
我正在尝试将我的代码从 一个大函数 重写为 oop。
如果我有这个,它会在 session.add(a1) # Unresolved reference
:
崩溃
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
from sqlalchemy.orm import *
Base = declarative_base()
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String, nullable=False)
city = Column(String, nullable=False)
user = relationship('User', back_populates="address")
class Main():
def __init__(self):
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
def insert(self):
# INSERT
a1 = Address()
a1.street = "Str 123"
a1.city = "City WTF"
session.add(a1) # Unresolved reference
session.commit()
if __name__ == '__main__':
Main().run()
我明白了。 session
是构造函数中的局部对象 (__init__
)。
但是如何放置对象 "directly to class"?
在 Java 我做了类似的事情:
public class Main {
Engine engine;
Session session;
public Main() {}
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)
}
private insert() {
//...
session.commit();
}
}
如何在 python 中完成? 抱歉提出愚蠢的问题,我是 python 新手。
-------------------- 编辑:
class Main():
engine = None # What I write here? How declare uninitialized object?
session = None # What I write here?
def __init__(self):
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
def insert(self):
# INSERT
a1 = Address()
a1.street = "Str 123"
a1.city = "City WTF"
self.session.add(a1) # Is possible to call session without "self"?
self.session.commit()
在 Java 你会做 this.session = ...
;在 Python 中是 self.session = ...
。
您正在 __init__
方法中初始化局部变量 session
并在该变量未知的方法中调用它。
在这两种情况下都使用 self.varialbe
使用self.session
在会话中保存变量
您 Main
class 中的方法看起来属于 Address
class.
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String, nullable=False)
city = Column(String, nullable=False)
# you are missing some fields you'll need eventually
state = Column(String, nullable=False)
zip_code = Column(String, nullable=False) # this can be an int if you don't have to worry about Canadian zips which have letters in them
user = relationship('User', back_populates="address")
def __init__(self, street, city, state, zip_code, user):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
self.user = user
def insert(self, session):
# INSERT
session.add(self)
session.commit()
您不应将会话创建为 class 的一部分,因为这样每次实例化 class 时都会创建一个新会话。将会话保留在全局 space 中并将其传递给需要它作为参数的 methods/functions( 不要使用 global
)。
现在一切都在正确的地方,你可以像这样使用它:
from models import session, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)
我正在尝试将我的代码从 一个大函数 重写为 oop。
如果我有这个,它会在 session.add(a1) # Unresolved reference
:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
from sqlalchemy.orm import *
Base = declarative_base()
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String, nullable=False)
city = Column(String, nullable=False)
user = relationship('User', back_populates="address")
class Main():
def __init__(self):
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
def insert(self):
# INSERT
a1 = Address()
a1.street = "Str 123"
a1.city = "City WTF"
session.add(a1) # Unresolved reference
session.commit()
if __name__ == '__main__':
Main().run()
我明白了。 session
是构造函数中的局部对象 (__init__
)。
但是如何放置对象 "directly to class"? 在 Java 我做了类似的事情:
public class Main {
Engine engine;
Session session;
public Main() {}
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)
}
private insert() {
//...
session.commit();
}
}
如何在 python 中完成? 抱歉提出愚蠢的问题,我是 python 新手。
-------------------- 编辑:
class Main():
engine = None # What I write here? How declare uninitialized object?
session = None # What I write here?
def __init__(self):
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
def insert(self):
# INSERT
a1 = Address()
a1.street = "Str 123"
a1.city = "City WTF"
self.session.add(a1) # Is possible to call session without "self"?
self.session.commit()
在 Java 你会做 this.session = ...
;在 Python 中是 self.session = ...
。
您正在 __init__
方法中初始化局部变量 session
并在该变量未知的方法中调用它。
在这两种情况下都使用 self.varialbe
使用self.session
在会话中保存变量
您 Main
class 中的方法看起来属于 Address
class.
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String, nullable=False)
city = Column(String, nullable=False)
# you are missing some fields you'll need eventually
state = Column(String, nullable=False)
zip_code = Column(String, nullable=False) # this can be an int if you don't have to worry about Canadian zips which have letters in them
user = relationship('User', back_populates="address")
def __init__(self, street, city, state, zip_code, user):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
self.user = user
def insert(self, session):
# INSERT
session.add(self)
session.commit()
您不应将会话创建为 class 的一部分,因为这样每次实例化 class 时都会创建一个新会话。将会话保留在全局 space 中并将其传递给需要它作为参数的 methods/functions( 不要使用 global
)。
现在一切都在正确的地方,你可以像这样使用它:
from models import session, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)