SageChevieDays-ObjectsAndClasses
system:sage


<h1>Objects and Classes in Python and Sage<a class="headerlink" title="Permalink to this headline" href="#objects-and-classes-in-python-and-sage"></a></h1>
<p>This tutorial is an introduction to object oriented programming in Python and Sage. It requires basic knowledges on imperative/procedural programming (the most common programming style) that is conditional instructions, loops, functions, but now further knowledge about objects and classes is assumed. It is designed as an alternating sequence of formal introduction and exercises. The solution if the exercises is given at the end.</p>
<div id="object-oriented-programming-paradigm" class="section">
<h2>Object oriented programming paradigm<a class="headerlink" title="Permalink to this headline" href="#object-oriented-programming-paradigm"></a></h2>
<p>The object oriented programming paradigm relies on the two following fundamental rules:</p>
<ol class="arabic simple">
<li>Any thing of the real (or mathematical) world which needs to be manipulated by the computer is modeled by an <strong>object</strong>.</li>
<li>Each object is an <strong>instance</strong> of some <strong>class</strong>.</li>
</ol>
<p>At this point, those two rules are a little meaningless, so let&rsquo;s give some more or less precise definition of the terms:</p>
<hr class="docutils" />
<dl class="docutils"> <dt><strong>object</strong></dt> <dd>a <strong>portion of memory</strong> which contains the information needed to model the real world thing.</dd> <dt><strong>class</strong></dt> <dd>defines the <strong>data structure</strong> used to store the objects which are instance of the class together with their <strong>behavior</strong>.</dd> </dl> 
<hr class="docutils" />
<p>Let&rsquo;s start with some examples: We consider the vector space over <img class="math" src="_images/math/156c0e43da2df99cae1c91cfcff9bfa48e8709c1.png" alt="\QQ" /> whose basis is indexed by permutations, and a particular element in it:</p>
</div>

{{{id=0|
F = CombinatorialFreeModule(QQ, Permutations())
el = 3*F([1,3,2])+ F([1,2,3])
el
///
B[[1, 2, 3]] + 3*B[[1, 3, 2]]
}}}

</div>
<p>In python, everything is an object so there isn&#8217;t any difference between types
and classes. On can get the class of the object <tt class="docutils literal"><span class="pre">el</span></tt> by:</p>
<div class="highlight-python">

{{{id=1|
type(el)
///
<class 'sage.combinat.free_module.CombinatorialFreeModule_with_category.element_class'>
}}}

</div>
<p>As such, this is not very informative. We&#8217;ll go back to it later. The data
associated to objects are stored in so called <strong>attributes</strong>. They are
accessed through the syntax <tt class="docutils literal"><span class="pre">obj.attributes_name</span></tt>:</p>
<div class="highlight-python">

{{{id=2|
el._monomial_coefficients
///
{[1, 2, 3]: 1, [1, 3, 2]: 3}
}}}

</div>
<p>Modifying the attribute modifies the objects:</p>
<div class="highlight-python">

{{{id=3|
el._monomial_coefficients[Permutation([3,2,1])] = 1/2
el
///
B[[1, 2, 3]] + 3*B[[1, 3, 2]] + 1/2*B[[3, 2, 1]]
}}}

</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">as a user, you are <em>not</em> supposed to do that by yourself (see
note on <a class="reference internal" href="#private-attributes"><em>private attributes</em></a> below).</p>
</div>
<p>As an element of a vector space <tt class="docutils literal"><span class="pre">el</span></tt> has a particular behavior:</p>
<div class="highlight-python">

{{{id=4|
2*el
///
2*B[[1, 2, 3]] + 6*B[[1, 3, 2]] + B[[3, 2, 1]]
}}}

{{{id=5|
el.support()
///
[[1, 2, 3], [1, 3, 2], [3, 2, 1]]
}}}

{{{id=6|
el.coefficient([1, 2, 3])
///
1
}}}

</div>
<p>The behavior is defined through <strong>methods</strong> (<tt class="docutils literal"><span class="pre">support,</span> <span class="pre">coefficient</span></tt>). Note
that this is true, even for equality, printing or mathematical operations:</p>
<div class="highlight-python">

{{{id=7|
el.__eq__(F([1,3,2]))
///
False
}}}

{{{id=8|
el.__repr__()
///
'B[[1, 2, 3]] + 3*B[[1, 3, 2]] + 1/2*B[[3, 2, 1]]'
}}}

{{{id=9|
el.__mul__(2)
///
2*B[[1, 2, 3]] + 6*B[[1, 3, 2]] + B[[3, 2, 1]]
}}}

</div>
<p>Some particular actions allows to modify the data structure of <tt class="docutils literal"><span class="pre">el</span></tt>:</p>
<div class="highlight-python">

{{{id=10|
el.rename(&quot;bla&quot;)
el
///
bla
}}}

</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The class is stored in a particular attribute called <tt class="docutils literal"><span class="pre">__class__</span></tt> the
normal attribute are stored in a dictionary called <tt class="docutils literal"><span class="pre">__dict__</span></tt>:</p>
<div class="highlight-python">

{{{id=11|
el.__class__
///
<class 'sage.combinat.free_module.CombinatorialFreeModule_with_category.element_class'>
}}}

{{{id=12|
el.__dict__
///
{'_monomial_coefficients': {[3, 2, 1]: 1/2, [1, 2, 3]: 1, [1, 3, 2]: 3}, '__custom_name': 'bla'}
}}}

</div>
<p>Lots of sage objects are not Python objects but compiled Cython
objects. Python sees them as builtin objects and you don&#8217;t have access to
the data structure. Examples include integers and permutation group
elements:</p>
<div class="last highlight-python">

{{{id=13|
e = Integer(9)
type(e)
///
<type 'sage.rings.integer.Integer'>
}}}

{{{id=14|
e.__dict__
///
<dictproxy object at 0x...>
}}}

{{{id=15|
e.__dict__.keys()
///
['__module__', '_reduction', '__doc__', '_sage_src_lines_']
}}}

{{{id=16|
id4 = SymmetricGroup(4).one()
type(id4)
///
<type 'sage.groups.perm_gps.permgroup_element.PermutationGroupElement'>
}}}

{{{id=17|
id4.__dict__
///
<dictproxy object at 0x...>
}}}

</div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Each objects corresponds to a portion of memory called its <strong>identity</strong> in
python. You can get the identity using <tt class="docutils literal"><span class="pre">id</span></tt>:</p>
<div class="last highlight-python">

{{{id=18|
id(el)  # random
///
139813642977744
}}}

{{{id=19|
el1 = el; id(el1) == id(el)
///
True
}}}

</div>
</div>
<div class="section" id="summary">
<h3>Summary<a class="headerlink" href="#summary" title="Permalink to this headline"></a></h3>
<p>To define some object, you first have to write a <strong>class</strong>. The class will
defines the methods and the attributes of the object.</p>
<dl class="docutils">
<dt><strong>method</strong></dt>
<dd>particular kind of function associated with an object used to get
information about the object or to manipulate it.</dd>
<dt><strong>attribute</strong></dt>
<dd>variables where the info about the object are stored;</dd>
</dl>
</div>
<div class="section" id="an-example-glass-of-beverage-in-a-restaurant">
<h3>An example: glass of beverage in a restaurant<a class="headerlink" href="#an-example-glass-of-beverage-in-a-restaurant" title="Permalink to this headline"></a></h3>
<p>Let&#8217;s write a small class about glasses in a restaurant:</p>
<div class="highlight-python">

{{{id=20|
class Glass(object):
       def __init__(self, size):
           assert size &gt; 0
           self._size = float(size)
           self._content = float(0.0)
       def __repr__(self):
           if self._content == 0.0:
               return &quot;An empty glass of size %s&quot;%(self._size)
           else:
               return &quot;A glass of size %s cl containing %s cl of water&quot;%(
                       self._size, self._content)
       def fill(self):
           self._content = self._size
       def empty(self):
           self._content = float(0.0)
///
}}}

</div>
<p>Let&#8217;s create a small glass:</p>
<div class="highlight-python">

{{{id=21|
myGlass = Glass(10); myGlass
///
An empty glass of size 10.0
}}}

{{{id=22|
myGlass.fill(); myGlass
///
A glass of size 10.0 cl containing 10.0 cl of water
}}}

{{{id=23|
myGlass.empty(); myGlass
///
An empty glass of size 10.0
}}}

</div>
<p>Some comments:</p>
<ol class="arabic simple">
<li>The method <tt class="docutils literal"><span class="pre">__init__</span></tt> is used to initialize the object, it is used by the
so called <strong>constructor</strong> of the class that is executed when calling <tt class="docutils literal"><span class="pre">Glass(10)</span></tt>.</li>
<li>The method <tt class="docutils literal"><span class="pre">__repr__</span></tt> is supposed to return a string which is used to
print the object.</li>
</ol>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p><strong>Private Attributes</strong></p>
<ul class="last simple" id="private-attributes">
<li>most of the time, the user should not change directly the
attribute of an object. Those attributes are called <strong>private</strong>. Since
there is no mechanism to ensure privacy in python, the usage is to prefix
the name by an underscore.</li>
<li>as a consequence attribute access is only made through methods.</li>
<li>methods which are only for internal use are also prefixed with an
underscore.</li>
</ul>
</div>
</div>
<div class="section" id="exercises">
<h3>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline"></a></h3>
<ol class="arabic simple">
<li>add a method <tt class="docutils literal"><span class="pre">is_empty</span></tt> which returns true if a glass is empty.</li>
<li>define a method <tt class="docutils literal"><span class="pre">drink</span></tt> with a parameter <tt class="docutils literal"><span class="pre">amount</span></tt> which allows to
partially drink the water in the glass. Raise an error if one asks to
drink more water than there is in the glass or a negative amount of
water.</li>
<li>Allows the glass to be filled with something other than water. The method
<tt class="docutils literal"><span class="pre">fill</span></tt> should accept a parameter <tt class="docutils literal"><span class="pre">beverage</span></tt>. The beverage is stored in
an attribute <tt class="docutils literal"><span class="pre">_beverage</span></tt>. Update the method <tt class="docutils literal"><span class="pre">__repr__</span></tt> accordingly.</li>
<li>Add an attribute <tt class="docutils literal"><span class="pre">_clean</span></tt> and methods <tt class="docutils literal"><span class="pre">is_clean</span></tt> and <tt class="docutils literal"><span class="pre">wash</span></tt>. At the
creation a glass is clean, as soon as it&#8217;s filled it becomes dirty, and must
be washed to become clean again.</li>
<li>Test everything.</li>
<li>Make sure that everything is tested.</li>
<li>Test everything again.</li>
</ol>
</div>
</div>
<div class="section" id="inheritance">
<h2>Inheritance<a class="headerlink" href="#inheritance" title="Permalink to this headline"></a></h2>
<p>The problem: object of <strong>different</strong> classes may share a <strong>common behavior</strong>.</p>
<p>For example, if one wants to deal now with different dishes (forks, spoons
...) then there is common behavior (becoming dirty and being washed). So the
different classes associated to the different kinds of dishes should have the
same <tt class="docutils literal"><span class="pre">clean</span></tt>, <tt class="docutils literal"><span class="pre">is_clean</span></tt> and <tt class="docutils literal"><span class="pre">wash</span></tt> methods. But copying and pasting
code is bad and evil ! This is done by having a base class which factorizes
the common behavior:</p>
<div class="highlight-python">

{{{id=24|
class AbstractDish(object):
       def __init__(self):
           self._clean = True
       def is_clean(self):
           return self._clean
       def state(self):
           return &quot;clean&quot; if self.is_clean() else &quot;dirty&quot;
       def __repr__(self):
           return &quot;An unspecified %s dish&quot;%self.state()
       def _make_dirty(self):
           self._clean = False
       def wash(self):
           self._clean = True
///
}}}

</div>
<p>Now one can reuse this behavior within a class <tt class="docutils literal"><span class="pre">Spoon</span></tt>:</p>
<div class="highlight-python">

{{{id=25|
class Spoon(AbstractDish):
       def __repr__(self):
           return &quot;A %s spoon&quot;%self.state()
       def eat_with(self):
           self._make_dirty()
///
}}}

</div>
<p>Let&#8217;s tests it:</p>
<div class="highlight-python">

{{{id=26|
s = Spoon(); s
///
A clean spoon
}}}

{{{id=27|
s.is_clean()
///
True
}}}

{{{id=28|
s.eat_with(); s
///
A dirty spoon
}}}

{{{id=29|
s.is_clean()
///
False
}}}

{{{id=30|
s.wash(); s
///
A clean spoon
}}}

</div>
<div class="section" id="id1">
<h3>Summary<a class="headerlink" href="#id1" title="Permalink to this headline"></a></h3>
<ol class="arabic">
<li><p class="first">Any class can reuse the behavior of another class. One says that the
subclass <strong>inherits</strong> from the superclass or that it <strong>derives</strong> from it.</p>
</li>
<li><p class="first">Any instance of the subclass is also an instance its superclass</p>
<div class="highlight-python">

{{{id=31|
type(s)
///
<class '__main__.Spoon'>
}}}

{{{id=32|
isinstance(s, Spoon)
///
True
}}}

{{{id=33|
isinstance(s, AbstractDish)
///
True
}}}

</div>
</li>
<li><p class="first">If a subclass redefines a method, then it replaces the former one. One says
that the subclass <strong>overloads</strong> the method. One can nevertheless explicitly
call the hidden superclass method.</p>
<div class="highlight-python">

{{{id=34|
s.__repr__()
///
'A clean spoon'
}}}

{{{id=35|
Spoon.__repr__(s)
///
'A clean spoon'
}}}

{{{id=36|
AbstractDish.__repr__(s)
///
'An unspecified clean dish'
}}}

</div>
</li>
</ol>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p><strong>Advanced superclass method call</strong></p>
<p>Sometimes one wants to call an overloaded method without knowing in which
class it is defined. On use the <tt class="docutils literal"><span class="pre">super</span></tt> operator</p>
<div class="highlight-python">

{{{id=37|
super(Spoon, s).__repr__()
///
'An unspecified clean dish'
}}}

</div>
<p>A very common usage of this construct is to call the __init__ method of the
super classes:</p>
<div class="last highlight-python">

{{{id=38|
class Spoon(AbstractDish):
       def __init__(self):
           print &quot;Building a spoon&quot;
           super(Spoon, self).__init__()
       def __repr__(self):
           return &quot;A %s spoon&quot;%self.state()
       def eat_with(self):
           self.make_dirty()
s = Spoon()
///
Building a spoon
}}}

{{{id=39|
s
///
A clean spoon
}}}

</div>
</div>
</div>
<div class="section" id="id2">
<h3>Exercises<a class="headerlink" href="#id2" title="Permalink to this headline"></a></h3>
<ol class="arabic simple">
<li>Modify the class <tt class="docutils literal"><span class="pre">Glasses</span></tt> so that it inherits from <tt class="docutils literal"><span class="pre">Dish</span></tt>.</li>
<li>Write a class <tt class="docutils literal"><span class="pre">Plate</span></tt> whose instance can contain any meals together with
a class <tt class="docutils literal"><span class="pre">Fork</span></tt>. Avoid at much as possible code duplication (hint:
you can write a factorized class <tt class="docutils literal"><span class="pre">ContainerDish</span></tt>).</li>
<li>Test everything.</li>
</ol>
</div>
</div>
<div class="section" id="sage-specifics-about-classes">
<h2>Sage specifics about classes<a class="headerlink" href="#sage-specifics-about-classes" title="Permalink to this headline"></a></h2>
<p>Compared to Python, Sage has its particular way to handles objects:</p>
<ul class="simple">
<li>Any classes for mathematical objects in Sage should inherits from
<tt class="docutils literal"><span class="pre">SageObject</span></tt> rather than from <tt class="docutils literal"><span class="pre">object</span></tt>.</li>
<li>Printing should be done through <tt class="docutils literal"><span class="pre">_repr_</span></tt> instead of <tt class="docutils literal"><span class="pre">__repr__</span></tt> to allows
for renaming.</li>
<li>More generally, Sage specific special methods are usually named <tt class="docutils literal"><span class="pre">_meth_</span></tt>
rather than <tt class="docutils literal"><span class="pre">__meth__</span></tt>. For example, lots of classes implement <tt class="docutils literal"><span class="pre">_hash_</span></tt>
which is used and cached by <tt class="docutils literal"><span class="pre">__hash__</span></tt>.</li>
</ul>
</div>
<div class="section" id="advanced-uses-of-classes-factories">
<h2>Advanced uses of classes: Factories<a class="headerlink" href="#advanced-uses-of-classes-factories" title="Permalink to this headline"></a></h2>
<p>The problem: the actual class of an object sometimes depend on the parameters
given to the constructor.</p>
<p>TODO !!!!!!</p>
</div>
<div class="section" id="solutions-to-the-exercises">
<h2>Solutions to the exercises<a class="headerlink" href="#solutions-to-the-exercises" title="Permalink to this headline"></a></h2>
<p>TODO !!!!</p>
<p>That all folks !</p>
</div>

{{{id=60|

///
}}}