파이썬 공부하는 비전공자 왕초보입니다.
클래스 파트를 배우던 와중에 특정 인스턴스에만 메서드를 추가하여 사용하는것이 가능한지 궁금하여
다음과 같이 해보니 오류가 뜨더군요;;
class MyClass:
a=10
NewInstance=MyClass()
print (NewInstance.a)
def NewInstance.doublenum(self,a):
return a*2
print (NewInstance.doublenum(3))
인스턴스에 직접 메서드를 추가하는것이 불가한가 싶어 구글에 검색해보니 다음과 같은 설명이 있더라고요
The problem comes when you want to attach a method to a single instance:
def foo:
print("foo")
class A:
def bar(self):
print ("bar")
a=A()
def barFighters(self):
print("barFighters")
a.barFighters=barFighters
a.barFighters()
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: barFighters() takes exactly 1 argument (0 given)
The function is not automatically bound when it's attached directly to an instance:
To bind it, we can use the MethodType function in the types module:
import types
a.barFighters = types.MethodType( barFighters, a )
a.barFighters()
제 코드랑 약간 다르지만 인스턴스에 메소드를 직접 추가하려면
def 인스턴스객체.메서드이름():
의 형태로는 원래 메서드 추가가 불가한 건가요?
보통 이런 경우엔 위의 글처럼 타입 모듈을 사용하나요 아니면 자식 클래스를 만들어 메서드를 추가한다음
그 자식클래스의 인스턴스를 만들어 사용하나요?
자비로운 가르침 한수 부탁드립니다ㅠ
댓글 분란 또는 분쟁 때문에 전체 댓글이 블라인드 처리되었습니다.