如何将日期的属性与类中的实例属性“日期”进行比较?

时间:2019-02-11 22:24:20

标签: python

我正在编写有关家庭作业问题的代码,其中我必须累加用户在特定年份的所有推文的长度。

我要在下面的 verbosity 方法的代码中尝试做的是将User类中date实例属性中的年份与该方法中的y参数进行比较。如果匹配,它将继续添加鸣叫的长度,即字符串。

我可以正确访问date属性和tweet.contents吗?

class Tweet:
    """A tweet, like in Twitter.

    === Attributes ===
    content: the contents of the tweet.
    userid: the id of the user who wrote the tweet.
    created_at: the date the tweet was written.
    likes: the number of likes this tweet has received.

    === Sample Usage ===

    Creating a tweet:
    >>> t = Tweet('Rukhsana', date(2017, 9, 16), 'Hey!')
    >>> t.userid
    'Rukhsana'
    >>> t.created_at
    datetime.date(2017, 9, 16)
    >>> t.content
    'Hey!'

    Tracking likes for a tweet:
    >>> t.likes
    0
    >>> t.like(1)
    >>> t.likes
    1
    >>> t.like(10)
    >>> t.likes
    11
    """
    # Attribute types
    content: str
    userid: str
    created_at: date
    likes: int    

    def __init__(self, who: str, when: date, what: str) -> None:
        """Initialize a new Tweet.

        >>> t = Tweet('Rukhsana', date(2017, 9, 16), 'Hey!')
        >>> t.userid
        'Rukhsana'
        >>> t.created_at
        datetime.date(2017, 9, 16)
        >>> t.content
        'Hey!'
        >>> t.likes
        0
        """
        self.content = what
        self.userid = who
        self.created_at = when
        self.likes = 0


class User:
    """A Twitter user.

    === Attributes ===
    userid: the userid of this Twitter user.
    bio: the bio of this Twitter user.
    follows: a list of the other users who this Twitter user follows.
    tweets: a list of the tweets that this user has made.
    """
    # Attribute types
    userid: str
    bio: str
    follows: List[User]
    tweets: List[Tweet]

    def __init__(self, id_: str, bio: str) -> None:
        """Initialize this User.

        >>> u = User('Rukhsana', 'Roller coaster fanatic')
        >>> u.userid
        'Rukhsana'
        >>> u.bio
        'Roller coaster fanatic'
        >>> u.follows
        []
        >>> u.tweets
        []
        """
        self.userid = id_
        self.bio = bio
        self.follows = []
        self.tweets = []


    def verbosity(self, y: int) -> int:
        """Return the number of characters in this User's tweets in year <y>.

        >>> u1 = User('Rukhsana', 'Roller coaster fanatic')
        >>> u1.tweet('The comet!!')
        >>> u1.tweet('Leviathan!!!!!')
        >>> u1.verbosity(date.today().year)
        25
        >>> u1.verbosity(2015)
        0
        """
        total = 0
            for tweet in self.tweets:
                if tweet.created_at.year == y:
                    total += len(tweet.content)
        return total

0 个答案:

没有答案
相关问题