Python #1 | Basic


Introduction

  • Basic Python Syntax


1. Data Types

  • String

    • Limiting floats to N demicmal points

      • round(1.23456, 4)

      • "{:.2f} / {:.3f}".format(1.2345, 1.2345)

      • f"{num:.2f}"

  • Set

    • add: add value to set

    • update: add multiples values to set

    • remove: remove specific value from set



2. Class

  • Class : A set of related variables and methods as a blueprint for creating an object

    • Methods (instance, static, class) are described in detail in the next chapter.
  • Object : declared as a class type,

  • Instance : when the object is allocated in memory and is actually used

class A:
    # class variable
    class_var = 0 

    def __init__(self): # 객체를 생성할때 사용
         # instance variable
        self.var1 = 1
        print('init')

    def __call__(self): # 마치 함수를 호출하는 것처럼 인스턴스를 호출할 수 있도록 만듦
        print('call')

>>> a = A() # init
>>> a() # call


3. Method

  • Instance Method : The most common method type. Able to access data and properties unique to each instance. (instance variables)

  • Static Method : Cannot access anything else in the class. Totally self-contained code.

    • can be defined with decorator @staticmethod
    • can be defined without self in argument
    • can be called without generate instance
    • usally independent to instance fields, but included in classes due to its logical reasons
  • Class Method: Can access limited methods in the class. Can modify class specific details.

class Rectangle:
    count = 0 # class variable

    def __init__(self, width, height):
        self.width, self.height = width, height
        Rectangle.count += 1 

    # Instance Method
    def calcArea(self):
        return self.width * self.height

    @staticmethod
    def isSquare(rect_w, rect_h):
        return rect_w == rect_h

    @classmethod
    def print_count(cls):
        print(cls.count)


4. Lambda

  • Lambda : is a disposable function that is used and discarded.

    • Instead of defining a simple function like a general function and using it, use it immediately and throw it away when needed.

    • Often used with map(func, iterable) and filter(func, iterable).

      • map returns the result of applying all func to iterable,

      • filter returns only elements that satisfy func among iterable

>> g = lambda x:x**2
>> g(8) # 64

# with map & filter
>>> list(map(lambda x:x+3, [1,2,3,4])) # [4, 5, 6, 7]
>>> list(filter(lambda x:x>0, range(-5,5))) #[1, 2, 3, 4]


5. Decorator

def time_check(func):
  def new_func(*args, **kwargs):
    start_time = time.time()
    result = func(*args, **kwargs)
    end_time = time.time()
    print('Elapsed:', end_time-start_time)
    return result
  return new_func

##### without decorator #####
def big_number(n):
  return n**n**n

new_func = time_checker(big_number)
new_func(6)  

##### with decorator #####
@time_check
def big_number(n):
  return n**n**n

big_number(6)