본문 바로가기
ProgramingLagnuage/Python

[중급] 파이썬 객체지향프로그래밍 tip 3가지

by TSpoons 2025. 2. 15.

1. init 메서드

  • init은 Python 클래스에서 생성자(constructor) 역할
  • 객체(Object)가 생성될 때 자동으로 호출되며, 초기 설정을 담당
  • 객체 생성과 동시에 데이터를 설정할 수 있어 편리

객체 생성과 동시에 데이터를 설정하여 편리

class DataCollector:
    def __init__(self, path="./data"):
        self.path = path  # 데이터 저장 경로 설정
        self.transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.5,), (0.5,))
        ])
        self.train_data = FashionMNIST(self.path, train=True, download=True, transform=self.transform)
        self.test_data = FashionMNIST(self.path, train=False, download=True, transform=self.transform)

    def get_train_dataset(self):
        return self.train_data

    def get_test_dataset(self):
        return self.test_data

2. super().init()

  • 부모 클래스의 메서드를 자식 클래스에서 호출할 때 사용하는 함수
  • 부모 클래스의 속성과 메서드를 그대로 상속
class Net(nn.Module):
    def __init__(self, img_size):
        super().__init__()  # nn.Module의 __init__() 호출 (부모 클래스 초기화)
        self.img_size = img_size
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)

        # Flatten 크기 계산
        flattened_size = (self.img_size // 2) * (self.img_size // 2) * 64
        self.fc1 = nn.Linear(flattened_size, 1024)
        self.fc2 = nn.Linear(1024, 128)
        self.fc3 = nn.Linear(128, 10)  # 10 classes

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.size(0), -1)  # Flatten
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

 

3. if name == "main"

  • 스크립트를 직접 실행할 때만 특정 코드가 실행되도록 하고 싶을 때
  • 다른 파일에서 import할 때 실행되지 않도록 하고 싶을 때
  • multiprocessing, threading 등의 병렬 프로그래밍을 사용할 때



if __name__ == "__main__":
    # 데이터셋 수집 및 정보 출력
    data_collector = DataCollector()
    
    # 데이터로더 생성
    dataloader = Dataloader(batch_size=128)
    train_loader = dataloader.get_train_loader(data_collector.get_train_dataset())
    test_loader = dataloader.get_test_loader(data_collector.get_test_dataset())

    # 모델 및 환경 설정
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    net = Net(img_size=28).to(device)

    # 학습 수행
    trainer = Trainer(
        net, train_loader, test_loader, device, 
        criterion=torch.nn.CrossEntropyLoss(), 
        optimizer=torch.optim.Adam(net.parameters(), lr=0.001),
    )

    # 모델 불러오기
    net.load_state_dict(torch.load("./saved_models/FashionMnistModel.pth", weights_only=True))  
    evaluator = Evaluator(net, device)

    # 정확도 평가 및 손실 그래프 출력
    evaluator.error_trend_plot(trainer.get_loss_values(), trainer.get_accuracy_values())

    # 예측 결과 확인
    predict_and_show_samples(net, test_loader, device)

 

 

 

 

결론

 

init : 객체가 생성될 때 초기화하는 생성자 메서드

super().init() : 부모 클래스의 속성과 메서드를 상속받을 때 사용

if name == "main" : 스크립트를 직접 실행할 때만 코드 실행

'ProgramingLagnuage > Python' 카테고리의 다른 글

[초급] 파이썬 - 함수  (0) 2025.03.09
[초급] 파이썬 리스트  (0) 2025.03.08
[중급] tensor라는 데이터 구조  (0) 2025.02.13