클래스 변수는 클래스의 모든 인스턴스(instance)들이 공유하는 변수이다. 인스턴스 변수와 달리, 클래스 변수는 클래스 자체에 속하며, 모든 인스턴스가 동일한 값을 가진다.
클래스 변수 정의 및 사용
클래스 변수는 클래스 블록 안에 직접 정의된다. 클래스 변수를 정의한 후에는 클래스 이름을 통해 접근하거나, 인스턴스 이름을 통해 접근할 수 있다.
class Person:
species = "Homo sapiens" # 클래스 변수
def __init__(self, name, age):
self.name = name # 인스턴스 변수
self.age = age # 인스턴스 변수
# 클래스 변수를 클래스 이름을 통해 접근
print(Person.species) # Homo sapiens 출력
# 객체 생성
person1 = Person("홍길동", 30)
person2 = Person("김철수", 25)
# 클래스 변수를 인스턴스를 통해 접근
print(person1.species) # Homo sapiens 출력
print(person2.species) # Homo sapiens 출력
# 클래스 변수의 값 변경
Person.species = "Human"
# 변경된 클래스 변수 값 확인
print(person1.species) # Human 출력
print(person2.species) # Human 출력
print(Person.species) # Human 출력
클래스 변수와 인스턴스 변수의 차이
클래스 변수: 클래스 자체에 속하며, 모든 인스턴스가 공유한다.
인스턴스 변수: 개별 인스턴스에 속하며, 각 인스턴스마다 고유한 값을 가진다.
class Dog:
species = "Canis lupus" # 클래스 변수
def __init__(self, name):
self.name = name # 인스턴스 변수
dog1 = Dog("Max")
dog2 = Dog("Buddy")
# 인스턴스 변수는 각 인스턴스마다 다를 수 있다.
print(dog1.name) # Max 출력
print(dog2.name) # Buddy 출력
# 클래스 변수는 모든 인스턴스가 공유한다.
print(dog1.species) # Canis lupus 출력
print(dog2.species) # Canis lupus 출력
# 클래스 변수 값 변경
Dog.species = "Canis familiaris"
print(dog1.species) # Canis familiaris 출력
print(dog2.species) # Canis familiaris 출력
getattr
함수
getattr
함수는 객체에서 속성의 값을 반환한다. 만약 속성이 존재하지 않으면 AttributeError
를 발생시키거나, 기본값을 반환할 수 있다.
class Car:
brand = "Toyota" # 클래스 변수
# 클래스 변수 조회
print(getattr(Car, 'brand')) # Toyota 출력
# 존재하지 않는 속성 조회
print(getattr(Car, 'model', 'Unknown')) # Unknown 출력
setattr
함수
setattr
함수는 객체에 속성을 설정한다. 속성이 존재하지 않으면 새로운 속성을 추가한다.
class Car:
brand = "Toyota" # 클래스 변수
# 클래스 변수 설정
setattr(Car, 'brand', 'Honda')
print(Car.brand) # Honda 출력
# 새로운 클래스 변수 추가
setattr(Car, 'model', 'Civic')
print(Car.model) # Civic 출력
delattr
함수
delattr
함수는 객체에서 속성을 삭제한다. 만약 속성이 존재하지 않으면 AttributeError
를 발생시킨다.
class Car:
brand = "Toyota" # 클래스 변수
# 클래스 변수 삭제
delattr(Car, 'brand')
# 삭제된 속성 접근 시도
try:
print(Car.brand)
except AttributeError as e:
print(e) # type object 'Car' has no attribute 'brand' 출력
클래스 및 인스턴스의 __dict__
속성
__dict__
속성은 객체의 모든 속성과 그 값을 포함하는 딕셔너리를 반환한다. 이를 통해 클래스 변수와 인스턴스 변수를 쉽게 확인할 수 있다.
class Animal:
kingdom = "Animalia" # 클래스 변수
def __init__(self, name):
self.name = name # 인스턴스 변수
# 클래스의 __dict__ 조회
print(Animal.__dict__)
# 인스턴스의 __dict__ 조회
animal1 = Animal("Tiger")
print(animal1.__dict__)