English 中文(简体)
在施工期间从**kwargs确定一个班级的属性
原标题:Setting attributes of a class during construction from **kwargs

这里的Lav noob

目前,Im与Kalkere合作,我有:

from __init__ import Base
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String
from sqlalchemy.orm import relationship

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    username = Column(String, unique=True)
    email = Column(String)
    password = Column(String)
    salt = Column(String)
    openids = relationship("OpenID", backref="users")

User.__table__.create(checkfirst=True)

#snip definition of OpenID class

def create(**kwargs):
    user = User()
    if "username" in kwargs.keys():
        user.username = kwargs[ username ]
    if "email" in kwargs.keys():
        user.username = kwargs[ email ]
    if "password" in kwargs.keys():
        user.password = kwargs[ password ]

    return user

/db/users.py,因此将使用:

from db import users
new_user = users.create(username="Carson", password="1234")
new_user.email = "email@address.com"
users.add(new_user) #this function obviously not defined yet

但是,<代码>create()中的代码是一个微小的 st,我很想知道,是否有更好的方式来做到这一点,这是否要求阶梯,如果在用户物体中添加任何标记,就会失败。 和:

for attribute in kwargs.keys():
    if attribute in User:
        setattr(user, attribute, kwargs[attribute])
    else:
        raise Exception("blah")

这样,我就能够把这一点放在自己的职能中(除非有希望已经存在吗?) 因此,我不得不再一次地做一下,这样,我就可以改变表格结构,而不修改这一法典。

任何建议?

最佳回答

我的建议是不进一步简化。 如果你指派武断的属性,你就会面临进入重要物体结构的风险。

我的简化做法是,在你使用一个字典时,删除<代码>.keys(;封隔检查和代号已经使用钥匙。

......

第二种想法是,你可以有一个包含已知安全特性的类别特性,然后在职能范围内检查这一特性,例如使用<代码>setattr(>。

问题回答

如果你不需要涵盖继承的属性,

def create(**kwargs):
    keys_ok = set(User.__dict__)
    user = User()
    for k in kwargs:
        if k in keys_ok:
            setattr(user, k, kwargs[k])

如果您do需要涵盖继承的属性,inspect.get members 能够提供帮助(根据惯例,避免成员的名字从强调开始,或你希望确保的其他人可以这样做)。

我还愿考虑(至少)发出警告,如果<代码>set(kwargs)-一套(钥匙s_ok)不是空的——即如果通过到<代码>create的一些名词被定为在创建时的论点;这或许是一件好事!





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...