简体   繁体   English

访问Python类中的属性?

[英]Accessing Attributes in Python Class?

I have the following 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

I am converting a dict to obj and then trying to access the is_authenticated method, when I do the following below: 当我执行以下操作时,我要将字典转换为obj,然后尝试访问is_authenticated方法:

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

it returns an error saying: 它返回一条错误信息:

'convert_to_obj' object has no attribute 'is_authenticated'

I don't know why it's doing this. 我不知道为什么要这么做。 Hopefully, some other eyes might be able to point out what I am doing wrong. 希望其他人可以指出我做错了什么。 Thanks 谢谢

@user2357112 is right (and good catch, because I wouldn't have seen it): @ user2357112是正确的(并且很好,因为我不会看到它):

DO NOT USE TABS IN PYTHON — EVER! 切勿在PYTHON中使用标签-永远!

That said, I have a few comments about your code. 也就是说,我对您的代码有一些评论。

First: 第一:

class convert_to_obj(object):

is a very bad name for a class. 对于一个班级来说是一个很不好的名字。 It'd be a good name for a function, though. 不过,这对于函数来说是个好名字。 You should better call it, for example: 您最好调用它,例如:

class DictObject(object):

That being said, I'd advice you to use existing tools for doing such a thing. 话虽如此,我建议您使用现有的工具来做这样的事情。 There's a powerful one called namedtuple , in the collections module. collections模块中有一个强大的名为namedtuple To do your thing, you could do: 要执行您的操作,您可以执行以下操作:

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)

which would give: 这将给:

>>> 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

all that being more readable and easy to use. 所有这些都更具可读性和易用性。


NB: for a list of dicts to convert, just make: 注意:要获取要转换的字典列表,只需进行以下操作:

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

And if you're working with a list of pairs instead of a dict: 如果您使用的是配对列表而不是字典:

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

So you don't need the extra leg work in the __init__() . 因此,您不需要在__init__()进行额外的操作。

HTH 高温超导

You've mixed tabs and spaces, so the is_authenticated definition is erroneously nested inside the definition of __init__ . 您混用了制表符和空格,因此is_authenticated定义错误地嵌套在__init__的定义内。 Turn on "show whitespace" in your editor to see the problem, and run Python with the -tt flag to make it tell you when you do something like this. 在编辑器中打开“显示空白”以查看问题,然后使用-tt标志运行Python,以使其在执行此类操作时告诉您。 To fix the problem, convert the tabs to spaces; 要解决此问题,请将制表符转换为空格。 your editor most likely has a function to do this automatically. 您的编辑器很可能具有自动执行此操作的功能。

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

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