简体   繁体   English

Python:如何在类内部定义名为“ class”的变量

[英]Python: How to define a variable named 'class' inside of a class

Im using flask with sqlalchemy. 即时通讯与SQLAlchemy的烧瓶。

I have a Model that is defined as such: 我有一个这样定义的模型:

class Employee(db.Model):
    id = Column(Integer)
    class = Column(Text) #Can I do this? I need a field named 'class'.

If not, then how can I define variables in python that are the same as keywords? 如果没有,那么我如何在python中定义与关键字相同的变量?

You can't define a variable with then name class , as class is a reserved keyword. 您不能使用名称class定义变量,因为class是保留关键字。

https://docs.python.org/2.5/ref/keywords.html https://docs.python.org/2.5/ref/keywords.html

2.3.1 Keywords 2.3.1关键字

The following identifiers are used as reserved words, or keywords of the language, a nd cannot be used as ordinary identifiers . 以下标识符用作保留字或语言的关键字,并且nd不能用作普通标识符 They must be spelled exactly as written here: 它们的拼写必须与此处完全相同:

and del from not while as elif 和del从不如精灵
global or with assert else if pass 全局或断言其他,如果通过
yield break except import print class 减产休息,但进口印刷除外
exec in raise continue finally is 在加薪的高管继续是
return def for lambda try 为lambda返回def尝试

If not then how can I define variables in python that are the same as keywords? 如果不是,那我该如何在python中定义与关键字相同的变量?

As suggested in the comments you can append a character (eg _ ) after the word, and that will compile fine. 如注释中所建议,您可以在单词后面添加一个字符(例如_ ),这样可以很好地编译。

Saying

class_ = Column('class', Text)

will give you an orm field known as "class_" corresponding to a column in your database named "class". 将为您提供一个orm字段,称为“ class_”,与您数据库中名为“ class”的列相对应。 It sounds like this may be what you are trying to do. 听起来这可能是您要尝试执行的操作。

It may or may not be the best thing to do. 最好不要做。 You may be better off doing something like 您最好做一些类似的事情

clas = Column(Text)

and intentionally spelling it "funny", just to keep things simpler in the long run. 并故意将其拼写为“有趣”,以确保从长远来看更简单。 SQLAlchemy is really happiest when the orm names are the same as the column names. 当orm名称与列名称相同时,SQLAlchemy确实是最幸福的。

(Does this address your question?) (这是您的问题吗?)

'class' is a protected word in Python, pretty much meaning that you can't overwrite it. “类”在Python中是一个受保护的词,几乎意味着您不能覆盖它。 If you want to have something similar to 'class', as a variable, then I suggest using 'Class' or 'class_(class name/topic)' to overcome your issue. 如果您希望将类似于“类”的内容用作变量,那么我建议您使用“类”或“ class_(类名/主题)”来解决您的问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM