Python:定义对象变量而不进行初始化

时间:2015-05-28 12:04:35

标签: python oop constructor class-variables

我正在尝试将我的代码从一个大函数重写为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__)。

但是我怎样才能把对象“直接放到课堂上”? 在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中做到这一点? 抱歉愚蠢的问题,我是蟒蛇新手。

---------------------编辑:

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()

4 个答案:

答案 0 :(得分:4)

在Java中你做this.session = ...;在Python中self.session = ...

答案 1 :(得分:2)

Main课程中的方法看起来属于Address课程。

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 )。

现在一切都在正确的位置,您可以像这样使用它:

from models import session, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)

答案 2 :(得分:1)

您正在session方法中初始化局部变量__init__,并在此变量未知的方法中调用它。

在两种情况下都使用self.varialbe

答案 3 :(得分:1)

使用self.session
在会话中保存变量