Why is count in quotes and how does hasattr work in an if statement?

Hm, I think your response may have shed some light on my confusion…but perhaps not. There is a count method in python that counts stuff correct? I believe in this exercise what the “”“f hasattr(element, ‘count’):”"" line of code is doing is checking to see if each element in the list has the ability to count and, if so, count how man times ‘s’ is in each element. Is that right? Or in this case is the ‘count’ used in this exercise and the general count method entirely different?

We’re aimed at determining if a class of object has a count attribute. If not, then we shouldn’t call that method on that object.

>>> (1).count(1)
Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
AttributeError: 'int' object has no attribute 'count'
>>> hasattr(1, 'count')
>>> [1].count(1)
>>> "1".count('1')
>>> {"1": 1}.count('1')
Traceback (most recent call last):
  File "<pyshell#108>", line 1, in <module>
    {"1": 1}.count('1')
AttributeError: 'dict' object has no attribute 'count'
>>> {"1": 1}.count(1)
Traceback (most recent call last):
  File "<pyshell#109>", line 1, in <module>
    {"1": 1}.count(1)
AttributeError: 'dict' object has no attribute 'count'

What we 'search" for doesn’t change anything if the method does not exist.

+1 on the rant for this question.

Extremely confusing with the whole ‘count’ attribute thing. I realize now that the element itself (via it’s data type) has the ‘count’ attribute, but still, that’s after 20 mins of Googling.

This question needs to be rewritten.


There are a few things I don’t understand about this lesson.

  1. Why is the attribute you’re looking for with hasattr() passed as an argument in quotation marks? So far we’ve used quotation marks with strings, so it’s not intuitive to use them when looking for a method.

  2. Since an attribute can be either a method or a variable, when we look for the "count" attribute using hasattr() and it comes back as True, how do we know it is a method that can be called and not just a variable of the class? Is it considered best practice to not have a variable and a method in the same class that both have the same name?

Because attribute names are type str.

The method only checks for attributes of a sequence class (str, list). It is up to us to determine (or know already) that the attribute is a method.


for element in how_many_s:
if hasattr(element, “count”):

Can anyone explain why “count” in hasattr(element, “count”) has to be a string? I thought we were checking if it was an attribute?

All attributes have keys of type ‘str’, so quotes are necessary in order to match.

1 Like

+1, I feel the same way.

1 Like

Can somebody explain what exactly are attributes. Reading all the comments it seems:
attribut = methods
Are there anymore attributs?

Thanks! :slight_smile:

Methods are attributes, but so are data values which are typically those given to the __init__() method on instantiation.

from math import sqrt as root

class Triangle:
    def check_sides(self, a, b, c):
        sum of any two sides must be greater than the other side
        if a + b > c and a + c > b and b + c > a:
            return True
        raise ValueError
    def __init__(self, a, b, c):    #  method
        self.check_sides(a, b, c)                    
        self.a = a                  #  attribute
        self.b = b                  #  attribute
        self.c = c                  #  attribute

    def area(self):                 #  method
        Heron's Area Formula for S-S-S triangle
        s = (self.a + self.b + self.c) / 2
        return root(s * (s - self.a) * (s - self.b) * (s - self.c))

abc = Triangle(60, 70, 80)          # instance
print (f"Where a = {abc.a}, b = {abc.b}, c = {abc.c}, Area = {abc.area():.3f}")
# Where a = 60, b = 70, c = 80, Area = 2033.316

fgh = Triangle(60, 20, 80)          # failed instance
# ValueError

Excellent explanation! Thank you very much! You breakdown exactly what is happening in the code.

The codeacademy lesson fails to do this and doesn’t give an example within the context of the lesson which is learning classes. I think code academy might need to review a number of lessons for lack of clarity in instruction and lack of context.


Chiming in like others here - I’ve been pretty happy with most of this course compared to other’s I’ve done. That being said, there have been a few lessons that are not so great at actually teaching the lesson. This one has been pretty bad. I’m not looking for hand holding by any means but people in this thread have done a better job of teaching the lesson and what we are actually supposed to do than the actual lesson did.



I think the explanation is that this is a very poorly designed course. I had the same frustrations with this, and many other lessons. You learn a new task, you go to practice the task, but they are asking you to perform a function that you haven’t been taught. By the time you do the research to find out how to do the random untaught function you’ve forgotten the task you were supposed to be learning in the first place. Its SO frustrating.


The Forums are where this course shines though. Invaluable answers to specific situations.

However same rant. I know coding is a lot of ‘looking things up’ and ‘figuring it out’ but thats what I’m paying for no? Some questions are worded so poorly I waste time trying to code something that fits exactly what they say, or what I assume to be truth in lieu of anything being said. I get that will be in my job if thats what I choose to do but…I have time to learn that later no?

Now I learn by doing, but a few people who whimsically undertook this journey with me all left CodeAcademy for other places. Just…food for thought.


Incredibly answered Sir.

1 Like

Hey doc Dennis, great example. @patrickd314 Thank you so much.

attribute and method, both are same. yes? I do not have a good understanding about what an attribute is?

An attribute is data point in a dictionary. There are set (unique) attributes in each instance of the class, compiled in the __init__() method, and there are shared attributes such as class variables and methods that are common to all the instances.

a_dict = A_class()                      #  an instance of a class

What a_dict may be comprised of,

  'attribute_name': 'attribute_value',  # attribute
  def get_attribute(self):
      return self.attribute_name        # method is also an attribute
1 Like

I think folks are forgetting our lesson on dir().

When we query hasattr() in this lesson, we aren’t looking for anything represented on screen. That is, we aren’t looking for count in how_many_s. We are actually looking for count in the attribuest of element[index] in how_many_s.

we see on screen:

how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

or, more visually understandable:

how_many_s = [
{‘s’: False},
[“a”, “c”, “s”, “d”, “s”]

Python sees:

how_many_s = [ <dict>, <str>, <int>, <list> ]

The effect of hasattr(element, "count") is that Python searches dir(element)' for count`:

dir(<dict>) looks like this:

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

As we can see, a dictionary has no count attribute/method and False is returned.

Meanwhile, dir(<str>) looks like this:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

As we can see, a string does in fact have an attribute/method called 'count' as it’s 4th non-dunder method.

This same process is effected on any user-created Class and can be seen by calling dir(UserCreatedClass) to see what hasattr() will be iterating through.