Objects and values

Before we start with classes, we will learn about objects.

What does object mean for programmers?

It's actually easy with Python - every value (that's something you can "store" into a variable) is an object. Some programming languages (e.g. JavaScript, C++, Java) also have values other than objects. And for example C doesn't have objects at all. But in Python there is no difference between value and object, so it's a little bit difficult to understand. On the other hand, you don't have to know the details.

The basic attribute of objects is that they contain data (information) and behaviour - instructions and/or methods how to work with data. For example, strings contain information (a sequence of characters) as well as useful methods such as upper and count. If strings were not objects, Python would have to have a lot more functions, such as str_upper and str_count. Objects connect data and functionality together.

You will maybe say that, for example, len is a function, and you will be correct. Python is not 100% an object oriented language. But the function len also works on objects which do not have anything in common with strings.

Classes

The data of each object is specific for each concrete object (e.g. "abc" contains different characters than "def"), but the functionality - the methods - are the same for all objects of the same type (class). For example, the string method count() could be written like this:

def count(string, character):
    sum = 0
    for c in string:
        if c == character:
            sum = sum + 1
    return sum

And although a different string will return a different value, the method itself is same for all strings.

This common behaviour is defined by the type or class of the object.

In previous versions of Python there was a difference between "type" and "class", but now they are synonyms.

You can find out type of an object by using the function type:

>>> type(0)
<class 'int'>
>>> type(True)
<class 'bool'>
>>> type("abc")
<class 'str'>
>>> with open('file.txt') as f:
...     type(f)
... 
<class '_io.TextIOWrapper'>

The function type returns some classes. What is a class? It's a description how every object of the same type behaves.

Most of the classes in Python are callable as if they were functions. This following code will create an object of the class we called:

>>> string_class = type("abc")
>>> string_class(8)
'8'
>>> string_class([1, 2, 3])
'[1, 2, 3]'

So it's behaving as the function str! Isn't it strange?

Now I have to apologise: materials for functions lied a bit. Functions str, int, float, etc., are actually classes.

>>> str
<class 'str'>
>>> type('abcdefgh')
<class 'str'>
>>> type('abcdefgh') == str
True

But we can call them as if they were functions. So classes contain not only the "description" how object of the class will behave, but they can also create objects.

Custom classes

Now we will try to create our own class.

Writing custom classes is useful when you want to use different objects with similar behaviour in your program. For example, a card game could have Card class, a web application could have a User class, and a spreadsheet application could have Row class.

Let's write a program that handles animals. First, you create a Kittie class which can meow:

class Kittie:
    def meow(self):
        print("Meow!")

Just as a function is defined by the def keyword, classes are defined by the class keyword. Then of course you have to continue with a colon and indentation of the class body. Similar as def creates a function, class creates a class and assigns it to the name of the class (in our example to Kittie).

It's a convention that classes are named with an uppercase first letter so they are not easily confused with "normal" variables.

Basic classes (str, int, etc.) don't start with an uppercase letter because of historic reasons – originally they were really functions.

In the class body, you define methods, which looks like functions. The difference is that class methods have self as the first argument, which we will explain later - meowing comes first:

# Creation of the object
kittie = Kittie()

# Calling the method
kittie.meow()

In this case you have to be really careful about uppercase letters: Kittie (with uppercase K) is the class - the description how kitties behave. kittie (lowercase k) is the object (an instance) of the Kittie class: a variable that represents a Kittie. That object is created by calling the class (same as we can create a string by calling str()).

Meow!

Attributes

Objects that are created from custom classes have one feature that classes like str don't allow: The ability to define class attributes - information that is stored by the instance of the class. You can recognise attributes by the period between class instance and the name of its attribute.

smokey = Kittie()
smokey.name = 'Smokey'

misty = Kittie()
misty.name = 'Misty'

print(smokey.name)
print(misty.name)

In the beginning we said that objects are connecting behaviour with data. Behaviour is defined in the class, data is stored in attributes. We can differentiate Kitties, for example, by their names because of the attributes.

By using a period after a class object, you can access the class methods as well as its attributes. What happens if an attribute has the same name as method? Try it!

misty = Kittie()
misty.meow = 12345
misty.meow()

Parameter self

Now we will briefly go back to methods, to be specific, we will go back to the parameter self.

Each method has access to any specific object that it's working on just because of parameter self. Now after you have named your kitties, you can use the self parameter to add the name to meowing.

class Kittie:
    def meow(self):
        print("{}: Meow!".format(self.name))

smokey = Kittie()
smokey.name = 'Smokey'

misty = Kittie()
misty.name = 'Misty'

smokey.meow()
misty.meow()

What just happened? The command smokey.meow called a method which when it's called assigns the object smokey as first argument to the function meow.

This is how a method is different from a function: A method "remembers" the object it is working on.

And that first argument which contains a specific object of the just created class is usually called self. You can of course call it differently, but other programmers will not like you. :)

Can such a method take more that one argument? It can - in that case, self will be substituted as the first argument, and the rest of the arguments will be taken from how you called the method. For example:

class Kittie:
    def meow(self):
        print("{}: Meow!".format(self.name))

    def eat(self, food):
        print("{}: Meow meow! I like {} very much!".format(self.name, food))

smokey = Kittie()
smokey.name = 'Smokey'
smokey.eat('fish')

Method __init__

There is another place where you can pass arguments to the class: when you create a new object (calling the class). You can easily solve the problem that you might see in the previous code: After the kittie object is created, you must add a name so the method meow can work.

You can also create classes by passing parameters when you are calling it:

smokey = Kittie(name='Smokey')

Python uses the __init__ method (2 underscores, init, 2 underscores) for this option. Those underscores indicate that this method name is somehow special. The method __init__ is actually called right when the object is being created, or in other words - when it's being initialized (init stands for initialization). So you can write it like this:

class Kittie:
    def __init__(self, name):
        self.name = name

    def meow(self):
        print("{}: Meow!".format(self.name))

    def eat(self, food):
        print("{}: Meow meow! I like {} very much!".format(self.name, food))

smokey = Kittie('Smokey')
smokey.meow()

And now there is no possibility to create a kittie without a name, and meow will work all the time.

There are many more methods with underscores, e.g. the __str__ method is called when you need to convert the object into a string:

class Kittie:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return '<Kittie named {}>'.format(self.name)

    def meow(self):
        print("{}: Meow!".format(self.name))

    def eat(self, food):
        print("{}: Meow meow! I like {} very much!".format(self.name, food))

smokey = Kittie('Smokey')
print(smokey)

Exercise: Cat

Now that you know how to create the kittie class, try to make a class for cats.

  • The Cat can meow with the meow method.
  • The Cat has 9 lives when she's created (she can't have more than 9 and less than 0 lives).
  • The Cat can say if she is alive (has more than 0 lives) with the alive method.
  • The Cat can lose lives (method takeoff_life).
  • The Cat can be fed with the eat method that takes exactly 1 argument - a specific food (string). If the food is fish, the Cat will gain one life (if she is not already dead or doesn't have maximum lives).

Řešení

And that's now everything about classes. Next time we will learn about inheritance. And also about doggies. :)

{
  "data": {
    "sessionMaterial": {
      "id": "session-material:2018/pyladies-en-prague:class:0",
      "title": "Classes",
      "html": "\n          \n    \n\n    <h1>Objects and values</h1>\n<p>Before we start with classes, we will learn about objects.</p>\n<p>What does <em>object</em> mean for programmers?</p>\n<p>It&apos;s actually easy with Python - every value (that&apos;s something you can &quot;store&quot;\ninto a variable) is an object.\nSome programming languages (e.g. JavaScript, C++, Java) also have \nvalues other than objects. And for example C doesn&apos;t have objects at all.\nBut in Python there is no difference between value and object, so\nit&apos;s a little bit difficult to understand. On the other hand, you don&apos;t have\nto know the details.</p>\n<p>The basic attribute of objects is that they contain data (information) and <em>behaviour</em> -\ninstructions and/or methods how to work with data.\nFor example, strings contain information (a sequence of characters) as well as\nuseful methods such as <code>upper</code> and <code>count</code>.\nIf strings were not objects, Python would have to have a lot more\nfunctions, such as <code>str_upper</code> and <code>str_count</code>.\nObjects connect data and functionality together.</p>\n<div class=\"admonition note\"><p>You will maybe say that, for example, <code>len</code> is a function, and you will be correct.\nPython is not 100% an object oriented language.\nBut the function <code>len</code> also works on objects which do not have anything in common with strings.</p>\n</div><h1>Classes</h1>\n<p>The data of each object is specific for each concrete object\n(e.g. <code>&quot;abc&quot;</code> contains different characters than <code>&quot;def&quot;</code>),\nbut the functionality - the methods - are the same for all objects of the same \ntype (class). For example, the string method <code>count()</code> could be\nwritten like this:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">count</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">,</span> <span class=\"n\">character</span><span class=\"p\">):</span>\n    <span class=\"nb\">sum</span> <span class=\"o\">=</span> <span class=\"mi\">0</span>\n    <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">string</span><span class=\"p\">:</span>\n        <span class=\"k\">if</span> <span class=\"n\">c</span> <span class=\"o\">==</span> <span class=\"n\">character</span><span class=\"p\">:</span>\n            <span class=\"nb\">sum</span> <span class=\"o\">=</span> <span class=\"nb\">sum</span> <span class=\"o\">+</span> <span class=\"mi\">1</span>\n    <span class=\"k\">return</span> <span class=\"nb\">sum</span>\n</pre></div><p>And although a different string will return a different value,\nthe method itself is same for all strings.</p>\n<p>This common behaviour is defined by the <em>type</em> or <em>class</em> of the object.</p>\n<div class=\"admonition note\"><p>In previous versions of Python there was a difference between &quot;type&quot;\nand &quot;class&quot;, but now they are synonyms.</p>\n</div><p>You can find out type of an object by using the function <code>type</code>:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"mi\">0</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;class &apos;int&apos;&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"bp\">True</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;class &apos;bool&apos;&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"s2\">&quot;abc&quot;</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;class &apos;str&apos;&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"k\">with</span> <span class=\"nb\">open</span><span class=\"p\">(</span><span class=\"s1\">&apos;file.txt&apos;</span><span class=\"p\">)</span> <span class=\"k\">as</span> <span class=\"n\">f</span><span class=\"p\">:</span>\n<span class=\"gp\">... </span>    <span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"n\">f</span><span class=\"p\">)</span>\n<span class=\"gp\">... </span>\n<span class=\"go\">&lt;class &apos;_io.TextIOWrapper&apos;&gt;</span>\n</pre></div><p>The function <code>type</code> returns some classes.\nWhat is a class? It&apos;s a description how every object of the same type\nbehaves.</p>\n<p>Most of the classes in Python are callable as if they were functions. \nThis following code will create an object of the class we called:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"n\">string_class</span> <span class=\"o\">=</span> <span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"s2\">&quot;abc&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"n\">string_class</span><span class=\"p\">(</span><span class=\"mi\">8</span><span class=\"p\">)</span>\n<span class=\"go\">&apos;8&apos;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"n\">string_class</span><span class=\"p\">([</span><span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"mi\">2</span><span class=\"p\">,</span> <span class=\"mi\">3</span><span class=\"p\">])</span>\n<span class=\"go\">&apos;[1, 2, 3]&apos;</span>\n</pre></div><p>So it&apos;s behaving as the function <code>str</code>! Isn&apos;t it strange?</p>\n<p>Now I have to apologise:\n<a href=\"/2018/pyladies-en-prague/beginners-en/functions/\">materials for functions</a>\nlied a bit. Functions <code>str</code>, <code>int</code>, <code>float</code>, etc., are actually classes.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">str</span>\n<span class=\"go\">&lt;class &apos;str&apos;&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"s1\">&apos;abcdefgh&apos;</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;class &apos;str&apos;&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"nb\">type</span><span class=\"p\">(</span><span class=\"s1\">&apos;abcdefgh&apos;</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"nb\">str</span>\n<span class=\"go\">True</span>\n</pre></div><p>But we can call them as if they were functions.\nSo classes contain not only the &quot;description&quot; how object of the class\nwill behave, but they can also create objects.</p>\n<h2>Custom classes</h2>\n<p>Now we will try to create our own class.</p>\n<p>Writing custom classes is useful when you want to use different objects \nwith similar behaviour in your program.\nFor example, a card game could have Card class, a web application could \nhave a User class, and a spreadsheet application could have Row class.</p>\n<p>Let&apos;s write a program that handles animals.\nFirst, you create a Kittie class which can meow:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Kittie</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;Meow!&quot;</span><span class=\"p\">)</span>\n</pre></div><p>Just as a function is defined by the <code>def</code> keyword, classes are\ndefined by the <code>class</code> keyword. Then of course you have to continue with a colon\nand indentation of the class body.\nSimilar as <code>def</code> creates a function, <code>class</code> creates a class and assigns it to the \nname of the class (in our example to <code>Kittie</code>).</p>\n<p>It&apos;s a convention that classes are named with an uppercase first letter so they\nare not easily confused with &quot;normal&quot; variables.</p>\n<div class=\"admonition note\"><p>Basic classes (<code>str</code>, <code>int</code>, etc.)\ndon&apos;t start with an uppercase letter because of historic\nreasons &#x2013; originally they were really functions.</p>\n</div><p>In the class body, you define methods, which looks like functions.\nThe difference is that class methods have <code>self</code> as the first argument,\nwhich we will explain later - meowing comes first:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"c1\"># Creation of the object</span>\n<span class=\"n\">kittie</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n\n<span class=\"c1\"># Calling the method</span>\n<span class=\"n\">kittie</span><span class=\"o\">.</span><span class=\"n\">meow</span><span class=\"p\">()</span>\n</pre></div><p>In this case you have to be really careful about uppercase letters:\n<code>Kittie</code> (with uppercase K) is the class - the description how kitties behave.\n<code>kittie</code> (lowercase k) is the object (an <em>instance</em>) of the Kittie class:\na variable that represents a Kittie.\nThat object is created by calling the class (same as we\ncan create a string by calling <code>str()</code>).</p>\n<p>Meow!</p>\n<h2>Attributes</h2>\n<p>Objects that are created from custom classes have one feature that\nclasses like <code>str</code> don&apos;t allow: The ability to define class <em>attributes</em> -\ninformation that is stored by the instance of the class.\nYou can recognise attributes by the period between class instance and the name of its attribute.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Smokey&apos;</span>\n\n<span class=\"n\">misty</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Misty&apos;</span>\n\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">)</span>\n</pre></div><p>In the beginning we said that objects are connecting behaviour with data.\nBehaviour is defined in the class, data is stored in attributes.\nWe can differentiate Kitties, for example, by their names because of the attributes.</p>\n<div class=\"admonition note\"><p>By using a period after a class object, you can access the class methods \nas well as its attributes.\nWhat happens if an attribute has the same name as method?\nTry it!</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">misty</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">meow</span> <span class=\"o\">=</span> <span class=\"mi\">12345</span>\n<span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">meow</span><span class=\"p\">()</span>\n</pre></div></div><h2>Parameter <code>self</code></h2>\n<p>Now we will briefly go back to methods, to be specific, we will go back\nto the parameter <code>self</code>.</p>\n<p>Each method has access to any specific object that it&apos;s working on just because of\nparameter <code>self</code>.\nNow after you have named your kitties, you can use the <code>self</code> parameter to add the name to meowing.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Kittie</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">))</span>\n\n<span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Smokey&apos;</span>\n\n<span class=\"n\">misty</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Misty&apos;</span>\n\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">meow</span><span class=\"p\">()</span>\n<span class=\"n\">misty</span><span class=\"o\">.</span><span class=\"n\">meow</span><span class=\"p\">()</span>\n</pre></div><p>What just happened? The command <code>smokey.meow</code> called a <em>method</em> which when it&apos;s called assigns the object\n<code>smokey</code> as first argument to the function <code>meow</code>.</p>\n<div class=\"admonition note\"><p>This is how a <em>method</em> is different from a <em>function</em>:\nA method &quot;remembers&quot; the object it is working on.</p>\n</div><p>And that first argument which contains a specific object of the just created class is\nusually called <code>self</code>.\nYou can of course call it differently, but other programmers will not like you. :)</p>\n<p>Can such a method take more that one argument?\nIt can - in that case, <code>self</code> will be substituted as the first argument,\nand the rest of the arguments will be taken from how you called the method.\nFor example:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Kittie</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">))</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">eat</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow meow! I like {} very much!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">))</span>\n\n<span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">()</span>\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Smokey&apos;</span>\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">eat</span><span class=\"p\">(</span><span class=\"s1\">&apos;fish&apos;</span><span class=\"p\">)</span>\n</pre></div><h2>Method <code>__init__</code></h2>\n<p>There is another place where you can pass arguments to the class:\nwhen you create a new object (calling the class).\nYou can easily solve the problem that you might see in the previous code:\nAfter the kittie object is created, you must add a name so the method\n<code>meow</code> can work.</p>\n<p>You can also create classes by passing parameters when you are calling it:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">(</span><span class=\"n\">name</span><span class=\"o\">=</span><span class=\"s1\">&apos;Smokey&apos;</span><span class=\"p\">)</span>\n</pre></div><p>Python uses the <code>__init__</code> method (2 underscores, <code>init</code>, 2 underscores) for this option.\nThose underscores indicate that this method name is somehow special. The method <code>__init__</code>\nis actually called right when the object is being created, or in other words - when it&apos;s\nbeing initialized (<code>init</code> stands for <em>initialization</em>).\nSo you can write it like this:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Kittie</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">name</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"n\">name</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">))</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">eat</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow meow! I like {} very much!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">))</span>\n\n<span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">(</span><span class=\"s1\">&apos;Smokey&apos;</span><span class=\"p\">)</span>\n<span class=\"n\">smokey</span><span class=\"o\">.</span><span class=\"n\">meow</span><span class=\"p\">()</span>\n</pre></div><p>And now there is no possibility to create a kittie without a name,\nand <code>meow</code> will work all the time.</p>\n<p>There are many more methods with underscores, e.g. the <code>__str__</code>\nmethod is called when you need to convert the object into a string:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Kittie</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">name</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"n\">name</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__str__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"s1\">&apos;&lt;Kittie named {}&gt;&apos;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">))</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">eat</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;{}: Meow meow! I like {} very much!&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">name</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">))</span>\n\n<span class=\"n\">smokey</span> <span class=\"o\">=</span> <span class=\"n\">Kittie</span><span class=\"p\">(</span><span class=\"s1\">&apos;Smokey&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">smokey</span><span class=\"p\">)</span>\n</pre></div><h2>Exercise: Cat</h2>\n<p>Now that you know how to create the kittie class, try to make a class for cats.</p>\n<ul>\n<li>The Cat can meow with the <code>meow</code> method.</li>\n<li>The Cat has 9 lives when she&apos;s created (she can&apos;t have more than 9 and less than 0 lives). </li>\n<li>The Cat can say if she is alive (has more than 0 lives) with the <code>alive</code> method.</li>\n<li>The Cat can lose lives (method <code>takeoff_life</code>).</li>\n<li>The Cat can be fed with the <code>eat</code> method that takes exactly 1 argument - a specific food (string).\nIf the food is <code>fish</code>, the Cat will gain one life (if she is not already dead or\ndoesn&apos;t have maximum lives).</li>\n</ul>\n<div class=\"solution\" id=\"solution-0\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/class/index/solutions/0/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <div class=\"highlight\"><pre><span></span><span class=\"k\">class</span> <span class=\"nc\">Cat</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>         <span class=\"c1\"># Init function does not have to take number of lives</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">lives_number</span> <span class=\"o\">=</span> <span class=\"mi\">9</span>   <span class=\"c1\"># as parameter &apos;cause that number is always the same.</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">meow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;Meow, meow, meeeoooow!&quot;</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">alive</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">lives_number</span> <span class=\"o\">&gt;</span> <span class=\"mi\">0</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">takeoff_life</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">alive</span><span class=\"p\">():</span>\n            <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;You can&apos;t kill a cat that is already dead, you monster!&quot;</span><span class=\"p\">)</span>\n        <span class=\"k\">else</span><span class=\"p\">:</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">lives_number</span> <span class=\"o\">-=</span> <span class=\"mi\">1</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">eat</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">food</span><span class=\"p\">):</span>\n        <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">alive</span><span class=\"p\">():</span>\n            <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;It&apos;s pointless to give food to dead cat!&quot;</span><span class=\"p\">)</span>\n            <span class=\"k\">return</span>\n        <span class=\"k\">if</span> <span class=\"n\">food</span> <span class=\"o\">==</span> <span class=\"s2\">&quot;fish&quot;</span> <span class=\"ow\">and</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">lives_number</span> <span class=\"o\">&lt;</span> <span class=\"mi\">9</span><span class=\"p\">:</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">lives_number</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span>\n            <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The cat ate a fish and gained 1 life!&quot;</span><span class=\"p\">)</span>\n        <span class=\"k\">else</span><span class=\"p\">:</span>\n            <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The cat is eating.&quot;</span><span class=\"p\">)</span>\n</pre></div>\n    </div>\n</div><p>And that&apos;s now everything about classes.\n<a href=\"/2018/pyladies-en-prague/beginners-en/inheritance/\">Next time</a> we will learn about inheritance.\nAnd also about doggies. :)</p>\n\n\n        "
    }
  }
}