AttributeError:' NoneType'对象没有属性' lower'

时间:2016-03-04 07:16:22

标签: python

我试图在类的 init 函数中调用类方法。我将一个字符串传递给函数,但错误显示它是一个无类型的对象。

class UserSettings(object):
    """Value object representing a user's settings."""
    def __init__(
            self, user_id, email, username=None):
        self.user_id = user_id
        self.email = email
        self.profile_picture_data_url = self.fetch_gravatar(email)


@classmethod
    def fetch_gravatar(cls, email):

        base_url = "http://www.gravatar.com/avatar/"
        avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"
        avatar_url += urllib.urlencode({'d':'retro', 's':str(AVATAR_SIZE)})            
        return avatar_url

这是错误:

Traceback (most recent call last):

  File "/home/travis/build/oppia/oppia/core/domain/user_services_test.py", line 78, in test_invalid_emails

    user_services.get_or_create_user('user_id', email)

  File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 297, in get_or_create_user

    user_settings = _create_user(user_id, email)

  File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 284, in _create_user

    preferred_language_codes=[feconf.DEFAULT_LANGUAGE_CODE])

  File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 55, in __init__

    self.profile_picture_data_url = self.fetch_gravatar(email)

  File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 129, in fetch_gravatar

    avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"

AttributeError: 'NoneType' object has no attribute 'lower'

2 个答案:

答案 0 :(得分:1)

  

AttributeError:' NoneType'对象没有属性' lower'

这告诉您正在尝试在单例对象lower上读取名为None的属性。

现在,您在lower的方法调用中使用email。因此,emailNone

答案 1 :(得分:0)

您必须使用值None或评估为None的参数调用方法。

# calling the class method:
>>> UserSettings.fetch_gravatar('a@example.com')
'http://www.gravatar.com/avatar/b418773a2c51fb9777a1648346fa7394?s=16&d=retro'

# create instance, call method:
>>> user_settings = UserSettings(user_id=1, email='jill@example.com')
>>> user_settings.fetch_gravatar('jill@example.com')
'http://www.gravatar.com/avatar/e84a7df193a44f643668b74a2bbfdde6?s=16&d=retro'

# calling with a No arguments gives TypeError
>>> UserSettings.fetch_gravatar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fetch_gravatar() takes exactly 2 arguments (1 given)

# calling with None gives your error:
>>> UserSettings.fetch_gravatar(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in fetch_gravatar
AttributeError: 'NoneType' object has no attribute 'lower'