# 클래스 : 함수(매소드)를 묶어 놓은 것
class ClassName:
def __init__(self, parameter1, parameter2):
self.attribute1 = parameter1
self.attribute2 = parameter2
def method1(self, parameter1, parameter2):
# 메서드 내용 작성
pass
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 객체 생성
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
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()
# 데코레이션 : 기존의 함수를 수정하지 않고 함수에 추가 기능을 넣을 때
@my_decorator 를 함수 바로 윗 줄에 써줌으로써 modify 가능
# 데코레이션 예시
# 기존의 함수를 따로 수정하지 않고도 추가 기능을 넣고 싶을 때 사용한다.
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 함수 활용 예
# Tensorflow 에서 연산을 좀 더 가속화 해줄 때 사용하지만, 계산량이 큰 연상이 다수 존재 할 때는 사용 전/후로 큰 차이는 발생하지 않는다.
# 작동 원리는 A>B>C 의 연산 과정을 3번 해야될 때, 데코를 이용하면 AAA > BBB > CCC 순으로 연산을 진행
# 계산량이 작을 때
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")
'Python 뿌시기' 카테고리의 다른 글
[NBcamp Python] ETC 파일 입출력 (glob, os, Split & Join) (1) | 2024.10.19 |
---|---|
[NBcamp Python] ETC (F-string, 리스트 캄프리헨션, 람다) (0) | 2024.10.19 |
[NBcamp Python] Function- Practical (0) | 2024.10.18 |
[NBcamp Python] Function - basic (0) | 2024.10.18 |
[NBcamp Python] While (0) | 2024.10.18 |