Classes vs Objects vs Instances vs Methods

Syntactic sugar & self

Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. For example, we use arr[i,j] but behind the scene, it's get_element(arr, vector(i,j)).

class MyClass()
    def method(arg):
        print(arg)

my_object = MyClass()
my_object.method('foo')
# TypeError: method() takes exactly 1 positional argument (2 given)

my_object.method('foo') means MyClass.method(my_object, 'foo'). That's why we need self or a decorator,

class MyClass():
    def method(self, arg):
        print(arg)
# DON'T NEED `self`
class MyClass():
    @staticmethod
    def method(self, arg):
        print(arg)

Get all attributes of a class

# CHECK THERE IS AN ATTRIBUTE
getattr(MyClass, 'report', None)
# if there is a class, it return this class' detail
# if not, return None
def props(cls):
    return [i for i in cls.__dict__.keys() if i[:1] != '_']

# access these attributes
properties = props(MyClass)
for att in properties:
    print(getattr(MyClass, att))
# Get dictionaries of all attributes & their values
MyClass.__dict__

Import local class

Suppose that we have a folders/files structure like below,

# ORIGINAL STRUCTURE
popai/
  processings/
    a.py # contains class ABC
    test/
      b.py
  lib/
    c.py # contains class XYZ
# UPDATED STRUCTURE
popai/
  __init__.py
  processings/
    __init__.py
    a.py # contains class ABC
    test/
      __init__.py
      b.py
  lib/
    c.py # contains class XYZ

We want import both classes ABC and XYZ,

# b.py
from popai.processings.a import ABC
# a.py
from popai.lib.c import XYZ

Just add __init__.py like in the right box above.