datatrail-jhu / python

A bonus course for DataTrail graduates who wish to learn python
https://datatrail-jhu.github.io/python/
Creative Commons Attribution 4.0 International
0 stars 2 forks source link

OOP #16

Open howardbaek opened 3 months ago

howardbaek commented 3 months ago

@cansavvy Below is the OOP section from https://github.com/datatrail-jhu/python/pull/10, which was taken out of that PR. See https://github.com/datatrail-jhu/python/pull/10#discussion_r1491133538.

Also, I've made a branch dedicated to OOP: 16-oop


Classes and Object Oriented Programming (OOP)

In R, the most widely used unit of composition for code is functions, and in Python, it is classes. Classes are how you organize and find methods in Python. This approach to code composition is called object oriented programming (OOP). Let's dive in the details of OOP.

An object is any entity that you want to store and process data about. Each object is an instance of a class in the computer's memory. A class is a template for creating objects. Creating an object from a class is called instantiation. It has properties and methods (functions for the class).

For example, we could have a class called Person. The properties of this class are what describe this Person class:

The methods of this class are the functions for this Person class:

Here is a simple Person class for demonstration purposes.

class Person:
  pass # `pass` means do nothing.

Person
#> <class '__main__.Person'>
type(Person)
#> <class 'type'>

instance = Person()
instance
#> <__main__.Person object at 0x102ba75e0>
type(instance)
#> <class '__main__.Person'>

Like the def statement, the class statement is used to create a Python class. First note the strong naming convention, classes are typically CamelCase, and functions are typically snake_case. After defining Person, you can interact with it, and see that it has type 'type'. Calling instance = Person() creates a new object instance of the class, which has type Person (ignore the main. prefix for now).