Python:无需初始化即可定义对象变量 [英] Python: define object variable without initialization
问题描述
我正在尝试将我的代码从一个大函数重写为oop。
I am trying to rewrite my code from one big function to oop.
如果我有此代码,它会在<$ c上崩溃$ c> session.add(a1)#无法解析的引用:
If I have this, it crash on 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()
我了解。 会话
是构造函数中的本地对象( __ init __
)。
I understand it. session
is local object in constructor (__init__
).
但是如何将对象直接放在类上?
在Java中,我会执行以下操作:
But how can I put object "directly to class"? In Java I do something like:
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新手。
How can I do it in python? Sorry for stupid question, I am python newbie.
------------------ ---编辑:
---------------------
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()
推荐答案
Main
类中的方法看起来像它们属于 Address
类中。
The methods on your Main
class look like they belong in the 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()
您不应将会话创建为类的一部分,因为那样的话,每次实例化一个类时,您都将创建一个新的会话。将会话保留在全局空间中,并将其传递给需要它作为参数的方法/函数(不要使用 global
)。
You shouldn't create the session as part of a class because then you will be creating a new one every time you instantiate a class. Keep the session in the global space and pass it in to your methods/functions that need it as a parameter (don't use global
).
现在一切都放在正确的位置,您可以像这样使用它:
Now with everything in right place you can use it like this:
from models import session, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)
这篇关于Python:无需初始化即可定义对象变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!