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

Sorry, you’ve lost me. What are we searching for? Where does count come into this?

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>
    (1).count(1)
AttributeError: 'int' object has no attribute 'count'
>>> 
>>> hasattr(1, 'count')
False
>>> 
>>> [1].count(1)
1
>>> "1".count('1')
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.

4 Likes

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.

3 Likes

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

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

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.

3 Likes

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.

2 Likes

woow!! TOP ANSWER/EXPLANATION

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.

3 Likes

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.

2 Likes

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