In my application I have a class User
and the class has id, ip, os
as attributes or values - not sure which one is the correct term.
I fetch the data needed and write it to a dictionary through json.loads()
, for example:
data = {'id': '111', 'ip': '127.0.0.1', 'os': 'windows'}
I use the data to create a new User i.e.
user1 = User(111, "127.0.0.", "windows")
I have a database with a table user
that stores the same attributes/values and I want to store that user in the database.
So is there a way to store the user in the databse without getting the data from the dictionary again?
答案 0 :(得分:1)
扩展@ junnytony的答案,你可以从字典中检索对象,使用简单的方法将对象设为字典。
示例:
class User(object):
def __init__(self, id=None, ip=None, os=None, input_dict=None):
if input_dict:
self.from_dict(input_dict)
else:
self.id = id
self.ip = ip
self.os = os
def from_dict(self, input_dict):
self.id = input_dict.get('id')
self.ip = input_dict.get('ip')
self.os = input_dict.get('os')
def to_dict(self):
return {'id': self.id, 'ip': self.ip, 'os': self.os}
def __repr__(self):
return "id: {0}, ip: {1}, os: {2}".format(self.id, self.ip, self.os)
user1 = User(1, "127.0.0.1", "windows")
dict1 = user1.to_dict()
dict1['id'] = 2
user2 = User(input_dict=dict1)
print user1
# id: 1, ip: 127.0.0.1, os: windows
print user2
# id: 2, ip: 127.0.0.1, os: windows
答案 1 :(得分:0)
Why would you need to get the data from the dictionary again? If you want to store your User
object why not just write a function that accesses User.id
, User.ip
and User.os
and passes it to the Sqlite interface?
If that solution doesn't work for you: you can create a method in your User
object that converts the objects attributes to a dictionary...something like User.to_dict()
. There is already the inbuilt __dict__
attribute of every object but the issue with using that directly is that it may contain other parameters that you don't want to push to the database layer.
Example:
Class User(object):
def __init__(id, ip, os):
self.id = id
self.ip = ip
self.os = os
def to_dict():
return {'id': self.id, 'ip': self.ip, 'os': self.os}