GA Logo

OOP in New Language


What you will learn

  • How to Create a Class
  • How to Instantiate a Class
  • Write a Constructor and Methods
  • Create an Inherited Class
  • Write Static Methods/Properties
  • Data Types Study

Below you'll see Javascript examples of Object Oriented Patterns and their new language Counterparts.

Creating and Instantiating a Class

In Javascript

// Creating a Class
class Dog {}

// Instantiation
const Sparky = new Dog();

In Python

// Creating a Class
class Dog:
    pass

// Instantiation
sparky = Dog()

The Constructor and Methods

In Javascript

// Creating a Class
class Dog {
  // The constructor runs when we instantiate a new instance
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // A Method
  bark() {
    console.log(`${this.name} barks`);
  }
}

// Instantiation
const Sparky = new Dog("Sparky", 4);
Sparky.bark();

in Python

# Creating a Class
class Dog:

    # The constructor runs when we instantiate a new instance
    def __init__(self, name, age):
        self.name = name
        self.age = name

    # A Method
    def bark(self):
        print(f"{self.name} barks")

# Instantiation
Sparky = Dog("Sparky", 4)
Sparky.bark()

Inheritance

In Javascript

// Creating a Class
class Dog {
  // The constructor runs when we instantiate a new instance
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // A Method
  bark() {
    console.log(`${this.name} barks`);
  }
}

class SmallDog extends Dog {
  constructor(name, age) {
    //Super calls the constructor of the parent class
    super(name, age);
  }

  //This will override the version of bark in the parent class
  bark() {
    console.log(`${this.name} yaps`);
  }
}

// Instantiation
const Sparky = new SmallDog("Sparky", 4);
Sparky.bark();

in Python

# Creating a Class
class Dog:

    # The constructor runs when we instantiate a new instance
    def __init__(self, name, age):
        self.name = name
        self.age = name

    # A Method
    def bark(self):
        print(f"{self.name} barks")

class SmallDog(Dog):

    def __init__ (self, name, age):
        # Super calls the constructor of the parent class
        super().__init__(name, age)

    #This will override the version of bark in the parent class
    def bark(self):
        print(f"{self.name} Yaps")

# Instantiation
Sparky = SmallDog("Sparky", 4)
Sparky.bark()

Static Methods and Properties

In Javascript

// Static Properties/Methods belong to the class, not the instance
class Calculator {
  static lastResult = 0;

  static calculate(num1, num2, operator) {
    Calculator.lastResult = eval(`${num1} ${operator} ${num2}`);
    return Calculator.lastResult;
  }

  static showLastResult() {
    console.log(Calculator.lastResult);
  }
}

Calculator.calculate(2, 2, "+");
Calculator.showLastResult();

In Python

# Static Properties/Methods belong to the class, not the instance
class Calculator:
    # Properties declared outside the constructor are class/static properties
    lastResult = 0

    @classmethod # Defines this as class method that receive cls instead of self
    def calculate(cls, num1, num2, operator):
        cls.lastResult = eval(f"{num1} {operator} {num2}")
        return cls.lastResult

    @staticmethod # defines this as static method that receives neither self/cls
    def showLastResult():
         print(Calculator.lastResult)

Calculator.calculate(2, 2, "+")
Calculator.showLastResult()

Python Numbers

Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to. Similarly, the is instance() function is used to check if an object belongs to a particular class.

  a = 6
  print(a, "is of type", type(a))
  print(a, "is integer number?", isinstance(5,int))

  a = 3.0
  print(a, "is of type", type(a))
  print(a, "is float number?", isinstance(2.0,float))

  a = 1+2j  # '1' is real part and '2j' is imaginary part
  print(a, "is of type", type(a))
  print(a, "is complex number?", isinstance(1+2j,complex))

Python Strings

String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.

s = '''Apple'''
print(s)
s = """Apple"""
print(s)
s = 'Apple'
print(s)
s = "Apple"
print(s)

s = "This is a string"  # s is my variable
print(s)
s = '''A multiline
string'''
print(s)

Activity

Python Data Types Study in REPL.it or in a blank github repo

Python is a whole new world compared to JavaScript, and we need to get our bearings. The basis behind any programming language is it's data types, so we'll be digging deeper into Python's built-in data types using the official Python documentation.

Documentation-Hunt

When you go digging, you find treasure! So grab a shovel (and your favorite browser) and let's go digging through the docs!

Quotes Mark the Spot

Ah, strings! We know them, we love them. Truly our favorite kind of ordered characters wrapped in quotes, there's nothing quite like a good string.

We're in Python Land, and the locals call this place "str Island" after the Python class str.

Here are a few maps of the area:

Counting Gold

What would we do without numbers? Just guess how much money we have? What a world that would be if we never knew how to count our coins!

We've caught sight of "Numeral Shore" off in the distance! They say the sands on this island multiply as you start to count them - pirates like yourself have been burried alive in their attempts to count them all.

Break out your maps! Time to get hunting.

Fountain of Truth (or False)

Booleans are the true (or false) MVPs of coding languages. They manage to do so much with two simple values. Python's True and False look like the taller, potentially more grown-up siblings of JavaScript's true and false, but they still act the same.

Let's get to exploring the power of Booleans by visiting the Fountain of Truth or False. Here's some maps of the area:

Resources to Learn More


Python Data Types Deep Dive