어쩌다보니 박준태가 또 조장이조 5차

2024. 8. 5. 23:00·모각코/어쩌다보니 박준태가 또 조장이조
728x90

python class 사용

class NameOfClass():
	def __init__(self,param1,param2):
    	self.param1 = param1
        self.param2 = param2
    def some_method(self):
    	#perform some action
    	print(self.param1)

 

class Sample():
	pass # 빈클래스 생성

x = Sample()

class Dog():
	
    def __init__(self,breed,name):
    	self.breed = breed
        self.name = name
x = Dog('lab','Sammy')

print(type(x)) -> __main__.Dog

class Animal():
	def __init__(self):
    	print('Animal Created!')
    def report(self):
    	print("Animal")
    def eat(self):
    	print('Eating!')

a = Animal()
a.eat()
a.report()

 

상속

class Dog(Animal):
	
    def __init__(self):
    	Animal.__init__(self)
        print("Dog Created!")
	def report(self): #overriding
    	print("I am a dog!")
d = Dog()
d.eat()
d.report()

특수 메서스 정의

class Book():
	
    def __init__(self,title,author,pages):
    	self.title = title
        self.author = author
        self.pages = pages
    
    def __repr__(self): # def __str__ 비슷하게 사용됨
    
    	return f"Title: {self.title}, Author: {self.author}"
	#출력하려는 문자열을 return하는 특수 메서드 정의
    def __len__(self):
    	return self.pages
        
mybook = Book("Python Rocks!",'Jose',250)
print(mybook)

length_book = len(mybook)
print(length_book)

 

class Account:
	def __init__(self,owner,balance=0):
    	self.owner = owner
        self.balance = balance
    
    def __repr__(self):
    	return f"Account Owner: {self.owner}, Balance: {self.balance}"
    
    def deposit(self,dep_amt):
    	self.balance = self.balance + dep_amt
        print("Deposit was accepted!")
        
    def withdrawal(self,wd_amt):
    	if self.balance >= wd_amt:
        	self.balance = self.balance - wd_amt
            print("Withdrawal successful")
     	else:
        	print("Funds not available!")

 

Decorators

def simple_func():
	#Do simple stuff
    return something

더 많은 기능을 수행한 다음 반환하게 하려고 할 때

1. 기존 함수에 코드를 추가해 기능을 더 넣는다.

2. 완전히 새로운 함수를 만들고 여기에 이전 코드와 새 코드를 추가

추가 기능을 제거하려면 어떻게 해야하는가?

이전 함수 다시 사용, 새 코드를 수동으로 삭제

 

Python에는 기존 함수에 새 기능을 추가할 수 있는 데코레이터가 있다.

@ 연산자를 사용해서 기존 함수 위에 배치한다.

@some_decorator
def simple_func():
	#Do simple stuff
    return something

decorator를 사용해서 기존에 가지고 있는 간단한 함수를 새로운 기능을 추가할 수 있게한다.

def hello(name='Jose'):
	print("the hello() func has been run")
    
    def greet():
    	return "	This is inside the greet()"
        
    def welcome():
    	return "	This is inside welcome()"
     
    if name == "Jose":
    	return greet
    else:
    	return welcome

x = hello()
x()
# 함수 안의 함수 함수실행이 아닌 함수 반환


def hello():
	return "Hi Jose"
def other(func):
	print("Some other code")
    #Assume that func passed in is a function!
    print(func())

other(hello)
# 함수를 인자로 전달

def new_decorator(func):
	def wrap_func():
    	print("some code before executing func")
        
        func()
        
        print("Code here, after executing func()")
    
    return wrap_func
    
 def func_needs_decorator():
 	print("Please decorate me!!")
    
 func_needs_decorator = new_decorator(func_needs_decorator)
 
 @new_decorator
 def func_needs_decorator():
 	print("Please decorate me!!")

 

728x90

'모각코 > 어쩌다보니 박준태가 또 조장이조' 카테고리의 다른 글

어쩌다보니 박준태가 또 조장이조 6차  (0) 2024.08.12
어쩌다보니 박준태가 또 조장이조 모각코 6차 모임 8.12.  (0) 2024.08.12
어쩌다보니 박준태가 또 조장이조 모각코 5차 모임 8. 5.  (0) 2024.08.05
어쩌다보니 박준태가 또 조장이조 4차  (0) 2024.07.29
어쩌다보니 박준태가 또 조장이조 모각코 4차 모임 7.29.  (0) 2024.07.29
'모각코/어쩌다보니 박준태가 또 조장이조' 카테고리의 다른 글
  • 어쩌다보니 박준태가 또 조장이조 6차
  • 어쩌다보니 박준태가 또 조장이조 모각코 6차 모임 8.12.
  • 어쩌다보니 박준태가 또 조장이조 모각코 5차 모임 8. 5.
  • 어쩌다보니 박준태가 또 조장이조 4차
Bello's
Bello's
개발하는 벨로
  • Bello's
    벨로의 개발일지
    Bello's
  • 전체
    오늘
    어제
    • 분류 전체보기 (199) N
      • 노예 일지 (7)
        • 스타트업 노예일지 (3)
      • CS 이론 (81)
        • 학과 수업 (4)
        • 알고리즘 (64)
        • 시스템 프로그래밍 (3)
        • 데이터 통신 (1)
        • 운영체제 (2)
        • 데이터베이스 (1)
      • project (3)
      • 나는 감자다. (4)
      • Spring (27)
      • 모각코 (45)
        • 절개와지조(모각코) (7)
        • 어쩌다보니 박준태가 조장이조 (11)
        • 어쩌다보니 박준태가 또 조장이조 (12)
      • LikeLion🦁 (20)
      • 캘리포니아 감자 (4)
      • OpenSource Contribute (1)
      • 우아한테크벨로 (1) N
        • 프리코스 회고록 (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    BFS
    자바
    감자
    백준
    DFS
    누적합
    타임리프
    Spring
    티스토리챌린지
    JPA
    회고록
    그래프 순회
    절개와지조
    뛰슈
    프리코스
    모각코
    어렵다
    오블완
    8기
    나는 감자
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Bello's
어쩌다보니 박준태가 또 조장이조 5차
상단으로

티스토리툴바