인스턴스 객체를 통해 변수나 함수의 이름을 찾는 순서
인스턴스 객체 영역 >>> 클래스 객체 영역 >>> 전역 영역
순서대로 해도 찾지 못하는 경우 AttributeError 예외가 발생
>>> class Person:
name = "Default Name"
>>> p1 = Person()
>>> p2 = Person()
>>> print("p1's name: ", p1.name)
p1's name: Default Name
>>> print("p2's name: :", p2.name)
p2's name: : Default Name
생성된 두 인스턴스 객체는 클래스의 데이터를 참조
p1, p2에는 아직 인스턴스 객체만의 특화된 데이터가 없기 때문에 클래스 객체의 데이터를 참조
>>> print("p1's name: ", p1.name)
p1's name: Myeong
>>> print("p2's name: ", p2.name)
p2's name: Default Name
인스턴스 객체의 특화된 데이터는 인스턴스의 이름공간에 저장
>>> class Person:
name = "Default Name"
>>> p1 = Person()
>>> p2 = Person()
>>> Person.title = "New title" <<< 클래스 객체에 새로운 멤버 변수 title 추가
>>> print("p1's title: ", p1.title) <<< 두 인스턴스 객체에서 모두 접근 가능
p1's title: New title
>>> print("p2's title: ", p2.title)
p2's title: New title
>>> print("Person's title: ", Person.title) <<< 클래스 객체에서도 접근 가능
Person's title: New title
클래스 객체의 데이터는 모든 인스턴스 객체에서 접근 가능
>>> print("p1's age: ", p1.age) <<< p1 객체에만 age 멤버 변수를 추가
p1's age: 20
>>> print("p2's age: ", p2.age) <<< p2 객체와 상위 Person 클래스에는 age 이름을 찾을 수 없음
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print("p2's age: ", p2.age)
AttributeError: 'Person' object has no attribute 'age'
멤버 메서드에서 self가 누락된 경우
>>> str = "NOT Class Member"
>>> class GString:
str = ""
def Set(self, msg):
self.str = msg
def Print(self):
print(str) <<< self를 이용해 클래스 멤버에 접근하지 않는 경우 이름이 동일한 전역 변수에 접근
>>> g = GString()
>>> g.Set("First Message")
>>> g.Print()
NOT Class Member
내장 속성 __class__를 이용해 클래스 이름공간의 멤버 변수인 data 값을 변경
>>> class Test:
data = "Default"
>>> i2 = Test()
>>> i1 = Test()
>>> i1.__class__.data = "modify the instance of class"
>>> print(i1.data)
modify the instance of class
>>> print(i2.data)
modify the instance of class
>>> i2.data = "only modify the i2"
>>> print(i1.data)
modify the instance of class
>>> print(i2.data)
only modify the i2
'컴퓨터 > Python' 카테고리의 다른 글
생성자, 소멸자 메서드 (0) | 2013.07.16 |
---|---|
클래스 객체와 인스턴스 객체의 관계 (0) | 2013.07.15 |
클래스 선언 (0) | 2013.07.15 |
제어문과 연관된 유용한 함수 (0) | 2013.07.12 |
break, continue, 그리고 else (0) | 2013.07.12 |