Python Language OOP: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 26: Line 26:
==<span id='Method'></span>Methods==
==<span id='Method'></span>Methods==
==Special Methods==
==Special Methods==
===<tt>__init__()</tt>===
The object instance initialization method.
class MyClass:
  def __init__(self, name, color):
    self.name = name
    self.color = color
</syntaxhighlight>
===<tt>__str__()</tt>===
===<tt>__str__()</tt>===
<code>__str__()</code> is used by <code>print()</code>, <code>str()</code> and the string formatters to produce a string representation of an instance.
<code>__str__()</code> is used by <code>print()</code>, <code>str()</code> and the string formatters to produce a string representation of an instance.

Revision as of 21:48, 15 March 2022

External

Internal

TODO

  • How to call a method from inside the constructor. If I try, the compiler says "Unresolved reference"

Overview

Everything in Python is an object, from numbers to modules. The language offers possibility of declaring custom types, and creating object instances for those types. Unlike modules, there can be multiple instances of the same type. Creation of new types is achieved by using the class syntax. The custom types such declared are no different, intrinsically, from the types already existing in the runtime. The existing types can be extended. An object contains data, in form of variables called attributes and behavior, in form of functions called methods.

Class

A new type (class) is defined with the class keyword.

class MyClass:
  def __init__(self):
    pass

The class may be declared with parentheses, but the IDE static checks find those as "redundant":

class MyClass():
  ...

Methods

Special Methods

__init__()

The object instance initialization method. class MyClass:

 def __init__(self, name, color):
   self.name = name
   self.color = color

</syntaxhighlight>

__str__()

__str__() is used by print(), str() and the string formatters to produce a string representation of an instance.

class MyClass:
  ...
  def __str__(self):
      return self.name + ', ' + self.color

Static Methods

Static Initialization at Class Level

To perform an initialization once, upon creation of the type in the class' namespace, place the code directly under the code definition: All methods placed into the class are also "executed" - like when defining a function in the global namespace - but they are not calling.

class MyClass:
  # executed only once upon creation of the type
  pattern = re.compile(r'^(\w+):(\w+)-(\w+)$')

  def __init__(self):
    ...
  def my_method(self):
    ...

Objects

To create an instance of a class, use the class name followed by left paranthesis, followed by constructor arguments, followed by the right parenthesis. If the constructor has no arguments, the parentheses are optional.

o = SomeClass
o2 = SomeOtherClass('something')

Initialization

Inheritance

Overriding

Polymorphism

.