Python

[Python 101] Class, Decoration

thebuck104 2024. 7. 4. 17:27

 

Class 의 기본 구조

class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

    def method1(self, parameter1, parameter2):
    # 메서드 내용 작성
        pass

 

 

Class와 Object의 관계

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 객체 생성
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

 

 

다형성 - Polymorphism

class Animal:
    def sound(self):
        print("Some generic sound")

class Dog(Animal):
    def sound(self):
        print("Woof")

class Cat(Animal):
    def sound(self):
        print("Meow")

# 다형성 활용
animals = [Dog(), Cat()]
for animal in animals:
    animal.sound()

 


 

Decoration

기존의함수를 수정하지 않고도,

함수에 기능 한 줄 정도 추가하고 싶을 때

 

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

 

 

예시) Tensorflow with Decoration

import tensorflow as tf

@tf.function  # The decorator converts `add` into a `Function`.
def add(a, b):
  return a + b

add(tf.ones([2, 2]), tf.ones([2, 2]))  #  [[2., 2.], [2., 2.]]


import timeit
conv_layer = tf.keras.layers.Conv2D(100, 3)

@tf.function
def conv_fn(image):
  return conv_layer(image)

image = tf.zeros([1, 200, 200, 100])

print("Eager conv:", timeit.timeit(lambda: conv_layer(image), number=10))
print("Function conv:", timeit.timeit(lambda: conv_fn(image), number=10))
print("Note how there's not much difference in performance for convolutions")