Object-oriented Python

From PrattWiki
Revision as of 03:10, 2 October 2019 by Maximumh (talk | contribs) (A simple guide to basic object-oriented programming in Python.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The concept of object-oriented programming originate from the natural world, which is natural to use Class and Instance. Class is an abstract concept referring to a general category of objects. For example, we can define a Class to be students, so instances of the defined Class are specific students such as Bart, Lisa, and Simpson.

The level of abstraction of object-oriented program is higher than functions, because a Class includes both data and operations of the data.

Data Encapsulation, inheritance, and Polymorphism are three fundamental aspects of object-oriented programming.

Class and Instance

A Class refers to an abstract template of codes, while a Instance is defined as specific objects based a Class. Every Instance shares the same function inherited from the Class, but data for each Instance might be different.

class Student(object):
    pass

The code above defines a Class. Right after the keyword class is the name of the class, which usually starts with an upper case letter. Then (object) indicates which class is the Student inherited from. If you don't have a specific class to inherit, use object since it is the root class where all class inherits.

After defining the class, we can create a instance for Student.

>>> class Student(object):
...     pass
...
>>> bart = Student() # bart is a instance of Student()
>>> bart
<__main__.Student object at 0x101be77f0>
>>> Student # Student is a class
<class '__main__.Student'>

Inheritance and Polymorphism

Properties of Instance

Multiple Inheritance

Enumeration