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 |