강의

멘토링

커뮤니티

Inflearn Community Q&A

dreaming18177639's profile image
dreaming18177639

asked

Python from Basics to Advanced Taught by Silicon Valley Engineers

Learning about Class Methods

파이썬 class method

Resolved

Written on

·

318

1

@classmethod

def hyundai(cls):

return cls("sedan")

여기서 cls를 다른 변수 이름으로 바꿔도 되나요?(클래스 가리킨다는것은 유지된체로)

이렇게 instance method, class method로 나뉘는것은 타언어에는 없고 달리 파이썬만의 특징인가요??

python알고리즘

Answer 1

0

altoformula님의 프로필 이미지
altoformula
Instructor

안녕하세요 남기정님,

  • cls는 다른 변수로 변경가능하지만, 혼자 보는 코드가 아닌이상, 기존의 컨벤션을 따라 가시는게 좋습니다.

  • instance method, class method는 다른 언어에서도 존재합니다. 예를 들자면, 자바에서도 존재합니다.

// instance method example
public class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    // Instance method
    public void printValue() {
        System.out.println("Value: " + value);
    }
}

// Usage:
MyClass obj = new MyClass(42);
obj.printValue(); // Output: Value: 42

// static(class) method
public class MathUtils {
    // Static method
    public static int add(int a, int b) {
        return a + b;
    }
}

// Usage:
int result = MathUtils.add(10, 20);
System.out.println(result); // Output: 30
dreaming18177639's profile image
dreaming18177639

asked

Ask a question