인스턴스 메서드와 달리 다른 인스턴스 속성에 접근하거나 다른 인스턴스 메서드를 호출하는 것은 불가능함.
팩토리 메서드를 작성할 때 유용함
정적 메서드
@staticmethod 데코레이터 사용하여 선언
첫번째 매개 변수가 할당 되지 않음
클래스의 일부로 선언할 필요 없지만 비슷한 메서드를 하나의 클래스에 두고 싶을때 사용
정적 메서드 내에서는 인스턴스, 클래스 속성에 접근하거나 호출하는 것이 불가능
class Test:
object_count = 0 # class variable
def __init__(self, age):
self.age = age
Test.object_count += 1
# instance method
def add(self, age):
return self.age + age
# class method
@classmethod
def count(cls):
return cls.object_count
# static method
@staticmethod
def static(name):
print(name)
# instance method
test = Test(10)
print(test.age)
# class method
t1 = Test(10)
print(t1.count())
t2 = Test(20)
print(t2.count())
# static method
t2.static('static')
상속 / super
부모 클래스(parent class, super class), 자식 클래스(child class, sub class)
메소드 오버라이딩 (method overriding)
부모 클래스의 메소드를 자식 클래스에서 재정의 하는것
파이썬은 다중상속이 가능함(c++가능, C#, Java 불가능)
# parent class
class Parent:
def __init__(self, name, age):
self.name = name
self.age = age
def showParent(self):
print(self.name, self.age)
# child class
class Child(Parent): # 상속
def __init__(self, name, age):
super().__init__(name, age) # parent class init() 상속
def showChild(self):
super().showParent() # method oeverriding
print('child show')
p = Parent('JS', 10)
p.showParent()
c = Child('TT', 20)
c.showParent() # 부모 클래스 함수도 사용 가능
c.showChild()
추상 클래스 (abstract class)
추상 클래스는 메서드의 이름만 존재하는(메서드 구현 없이) 클래스
부모 클래스에 메서드만을 정의하고, 이를 상속 바은 클래스가 해당 메서드를 구현하도록 강제하기 위해서 사용함
# parent class
class Car:
@abstracmethod
def drive(self):
pass
class K5(Car):
def drive(self):
print('k5 drive')
car_k5 = K5()
string = 'hello'
# 변경 안됨
string.replace('h', 'H')
# 변경 가능. 다시 binding 해줘야함
string = string.replace('h', 'H')
문자열 인덱싱(indexing)
# indexing
str = hello
# 첫번째 문자
print(str[0])
# 세번째 문자
print(str[2])
# 마지막 문자
print(str[-1])
# 마지막 문자만 빼고
print(str[:-1])
문자열 슬라이싱(slicing)
string [start:end:step]
str = hello world
# 전체 출력
print(str)
# world 출력
print(str[6:10])
print(str[6:])
print(str[-5:])
# slicing [start : end : step]
print(str[::2])
print(str[1::2])
print(str[:4:2])
# 문자열 뒤집기
print(str[::-1])
replace 함수 - 문자열 변환
string = '111,222,333,444'
# , 를 - 으로 변경
string1 = string.replace(',', '-')
print(string1)