简体   繁体   English

为什么类实例在初始化时返回None

[英]Why class instance return None when it has initialized

I had a class as below 我有一节课如下

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Student(Base):
    __tablename__ = 'students'

    student_id = Column(Integer, primary_key=True)
    address = Column(String)
    name = Column(String)

    def __init__(self, address, name):
        self.address = address
        self.name = name

below is my call 以下是我的电话

def test_Student(self):
        from School.Student import Student
    address = 'India'
        name = 'Team A'

        student = Student(address,name)
        print student.student_id

student.student_id is returning None , student.student_id is returning None

why it is returning None ? 为什么它返回无? Shall i write test case as assertIsNone . 我应该把测试用例写成assertIsNone

Your student object is transient and does not have any identity in the database. 您的student对象是暂时的 ,并且在数据库中没有任何标识。 Assuming student_id is generated automatically, it will be None till you persist this object in the session. 假设student_id是自动生成的,在您将此对象保留在会话中之前,它将为None

session.add(student)
session.flush()

However, if you are writing tests, be careful that you do not commit your session (and hence add test data to the DB). 但是,如果您正在编写测试,请注意不要提交会话(因此将测试数据添加到数据库)。 This would involve opening a new transaction for every test and rolling it back at the end of the test 这将涉及为每个测试打开一个新事务,并在测试结束时将其回滚

您需要先保存学生才能获得自动增加的ID。

session.add(student)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么即使已初始化该类变量也为None? - Why this class variable is None even though it has been initialized? 声明Class实例时如何返回None - How to return None while declaring Class instance 在初始化类后引用该类时,如何使类返回对象? - How to make a Class return an object when the class is referenced after it has been initialized? 为什么 class.__weakref__ 不是 None,而 instance.__weakref__ 是 None? - Why is class.__weakref__ not None, while instance.__weakref__ is None? 为什么在输入列表 [0] 时返回 None? - Why Does This Return None when entering a list[0]? 为什么用于创建实例的python gcloud discovery api返回None? - Why does python gcloud discovery api for creating instance return None? 为什么在描述符类的__get__中需要“if instance is None”? - why do you need “if instance is None” in __get__ of a descriptor class? 新的 class 实例未初始化 - new class instance not being initialized 导入包含类的文件时,是否初始化 class 属性? - When importing a file that has classes, do class attributes get initialized? 当值不是 None 时,如何用另一个实例覆盖 attrs class 实例 - How to override an attrs class instance with another one when the values are not None
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM