0

I created this class earlier.

class Dog():
    """A simple attempt to model a dog."""

    def __init__(self, name, age):
        """Initialise name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

Now, the book I am reading says the following

Because these methods don’t need additional information like a name or age, we just define them to have one parameter, self.

I'm confused by what this means.

Does this mean that when we pass the parameter self, the method has automatic access to the attributes self.name and self.age?

The book in question is Python Crash Course by Eric Mattes.

martineau
  • 119,623
  • 25
  • 170
  • 301
user3416724
  • 143
  • 2
  • 6
  • Yes you are correct – RustyShackleford Jul 12 '17 at 21:51
  • 1
    You have access to the attributes of any parameters you receive. In this case, the only one you care about is `self`. – Barmar Jul 12 '17 at 21:52
  • @azalea I don't think this is a duplicate as that post also makes reference to ruby but I am discussing the subject in a different context. – user3416724 Jul 12 '17 at 21:53
  • 1
    In a nutshell, with `d = Dog("bob", 10)`, `d.sit()` is equivalent to `Dog.sit(d)`. – chepner Jul 12 '17 at 21:53
  • @Barmar what does the line `Because these methods don’t need additional information like a name or age` mean though, because that's the bit that seems to be confusing me! – user3416724 Jul 12 '17 at 21:53
  • 2
    I think that's just drawing a contrast to the `__init__` method which takes two additional arguments. The `sit` method doesn't need additional arguments because the `name` attribute has already been set on `self`. – Blckknght Jul 12 '17 at 21:56
  • 1
    It means exactly what you have understood. The author of the book seems to be not very clear: _"Because these methods **don’t need additional information like a name**..."_ `sit(self)` **is** accessing `name`: `self.name.title()`. However, `sit()` can get this info from self because it was stored as an attribute. – AGN Gazer Jul 12 '17 at 21:57

0 Answers0