我有以下代码,不知何故该类不尊重自我。 name。,当我访问函数中的类变量时,它抱怨self.variable不是全局变量。有什么想法吗?
from sqlalchemy import Column, ForeignKey, Integer , String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base=declarative_base()
class Designs(Base):
__tablename__='designs'
design_name=Column(String(80),nullable=False,primary_key=True)
@property
def serialize(self):
return{
'design_name': self.design_name,
}
当我访问类时,design_name就在那里,但不知何故python抱怨它没有被声明为全局?有任何想法吗?
让我们说使用Designs类声明的temp,并填充了design_name
的值 print temp.design_name
print temp.serialize()
xpc_fp <----- print i.design_name works
serialize命令不起作用**并给出以下错误:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "database_setup.py", line 149, in serialize
'design_name': self.design_name,
NameError: global name 'design_name' is not defined
答案 0 :(得分:1)
您将序列化定义为属性 - 因此您应将其视为属性。
from sqlalchemy import Column, ForeignKey, Integer , String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base=declarative_base()
class Designs(Base):
__tablename__='designs'
design_name=Column(String(80),nullable=False,primary_key=True)
@property
def serialize(self):
return{
'design_name': self.design_name,
}
temp = Designs(design_name='HELLO THERE')
print(temp.design_name)
print(temp.serialize)
所以从.serialize调用中删除括号
输出:
你好
{'design_name':'HELLO THERE'}