-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
해결됨
파이썬 class method
23.07.22 14:11 작성 조회수 202
1
@classmethod
def hyundai(cls):
return cls("sedan")
여기서 cls를 다른 변수 이름으로 바꿔도 되나요?(클래스 가리킨다는것은 유지된체로)
이렇게 instance method, class method로 나뉘는것은 타언어에는 없고 달리 파이썬만의 특징인가요??
답변을 작성해보세요.
0
미쿡엔지니어
지식공유자2023.07.22
안녕하세요 남기정님,
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
답변 1