gpt4 book ai didi

python - 访问 Python 类中的属性?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:50 27 4
gpt4 key购买 nike

我有以下类(class):

class convert_to_obj(object):
def __init__(self, d):
for llist in d:
for a, b in llist.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, obj(b) if isinstance(b, dict) else b)

def is_authenticated(self):
username = self.username
password = self.password
if username and password:
return True

我正在将字典转换为 obj,然后尝试访问 is_authenticated 方法,当我执行以下操作时:

new_array = [{'username': u'rr', 'password': u'something', }]
user = convert_to_obj(new_array)
user.is_authenticated()

它返回一个错误说:

'convert_to_obj' object has no attribute 'is_authenticated'

我不知道为什么会这样。希望其他人的眼睛能够指出我做错了什么。谢谢

最佳答案

@user2357112 是对的(而且很好,因为我不会看到它):

DO NOT USE TABS IN PYTHON ­— EVER!

也就是说,我对您的代码有几点意见。

首先:

class convert_to_obj(object):

是一个非常糟糕的类名。不过,这将是一个很好的函数名称。你最好这样调用它,例如:

class DictObject(object):

话虽这么说,我还是建议您使用现有工具来做这样的事情。有一个强大的叫namedtuple ,在 collections 模块中。为了做你的事,你可以这样做:

from collections import namedtuple

# Create a class that declares the interface for a given behaviour
# which will expect a set of members to be accessible
class AuthenticationMixin():
def is_authenticated(self):
username = self.username
password = self.password
# useless use of if, here you can simply do:
# return username and password
if username and password:
return True
# but if you don't, don't forget to return False below
# to keep a proper boolean interface for the method
return False

def convert_to_object(d): # here that'd be a good name:
# there you create an object with all the needed members
DictObjectBase = namedtuple('DictObjectBase', d.keys())
# then you create a class where you mix the interface with the
# freshly created class that will contain the members
class DictObject(DictObjectBase, AuthenticationMixin):
pass
# finally you build an instance with the dict, and return it
return DictObject(**d)

这会给出:

>>> new_array = [{'username': u'rr', 'password': u'something', }]
>>> # yes here I access the first element of the array, because you want
>>> # to keep the convert_to_object() function simple.
>>> o = convert_to_object(new_array[0])
>>> o
DictObject(password='something', username='rr')
>>> o.is_authenticated()
True

所有这些都更具可读性和易用性。


注意:对于要转换的字典列表,只需:

>>> objdict_list = [convert_to_object(d) for d in new_array]
>>> objdict_list
[DictObject(password='something', username='rr')]

如果您使用的是对列表而不是字典:

>>> tup_array = [('username', u'rr'), ('password', u'something')]
>>> {t[0]:t[1] for t in tup_array}
{'password': 'something', 'username': 'rr'}

因此您不需要在 __init__() 中做额外的工作。

HTH

关于python - 访问 Python 类中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36090648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com