그만큼 클래스메소드() 주어진 함수에 대한 클래스 메서드를 반환하는 Python의 내장 함수입니다.
Python 구문의 classmethod()
통사론: 클래스메소드(함수)
매개변수: 이 함수는 함수 이름을 매개변수로 받아들입니다.
반환 유형: 이 함수는 변환된 클래스 메서드를 반환합니다.
Python 클래스 메소드() 함수
classmethod() 메서드는 객체가 아닌 클래스에 바인딩됩니다. 클래스 메소드는 클래스와 객체 모두에서 호출할 수 있습니다. 이러한 메서드는 클래스나 개체를 사용하여 호출할 수 있습니다.
클래스 메소드와 정적 메소드
기본적인 차이점은 Python의 클래스 메소드와 정적 메소드 클래스 메서드와 정적 메서드를 언제 사용해야 할까요? 파이썬 .
- 클래스 메서드는 cls를 첫 번째 매개 변수로 사용하지만 정적 메서드에는 특정 매개 변수가 필요하지 않습니다.
- 클래스 메서드는 클래스 상태에 액세스하거나 수정할 수 있지만 정적 메서드는 클래스 상태에 액세스하거나 수정할 수 없습니다.
- 일반적으로 정적 메서드는 클래스 상태에 대해 아무것도 모릅니다. 이는 일부 매개변수를 사용하고 해당 매개변수에 대해 작동하는 유틸리티 유형 메소드입니다. 반면에 클래스 메소드에는 클래스가 매개변수로 있어야 합니다.
- Python에서 @classmethod 데코레이터를 사용하여 클래스 메서드를 만들고 @staticmethod 데코레이터를 사용하여 Python에서 정적 메서드를 만듭니다.
Python의 클래스 메소드 예
간단한 클래스 메소드 생성
이번 예제에서는 Python에서 클래스 메서드를 만드는 방법을 살펴보겠습니다. 이를 위해 멤버 변수 코스를 사용하여 Geeks라는 클래스를 만들고 개체를 인쇄하는 buy라는 함수를 만들었습니다. 이제 우리는 메소드를 통과했습니다.Geeks.purchase>다음을 사용하여 클래스 메소드로@classmethod>메소드를 클래스 메소드로 변환하는 데코레이터. 클래스 메소드를 사용하면 함수 객체를 생성하지 않고도 클래스 이름 Geeks를 직접 사용하여 함수 구매를 호출할 수 있습니다.
파이썬3
문자열에 정수
class> geeks:> >course>=> 'DSA'> >def> purchase(obj):> >print>(>'Purchase course : '>, obj.course)> geeks.purchase>=> classmethod>(geeks.purchase)> geeks.purchase()> |
>
>산출
Purchase course : DSA>
classmethod()를 사용하여 클래스 메소드 생성
이 줄을 만들기 전에 print_name 클래스 메소드를 생성했습니다. print_name() 클래스가 아닌 객체로만 호출할 수 있습니다. 이제 이 메소드는 클래스 메소드로 호출할 수 있습니다. print_name() 메소드를 클래스 메소드라고 합니다.
파이썬3
class> Student:> ># create a variable> >name>=> 'Geeksforgeeks'> ># create a function> >def> print_name(obj):> >print>(>'The name is : '>, obj.name)> # create print_name classmethod> # before creating this line print_name()> # It can be called only with object not with class> Student.print_name>=> classmethod>(Student.print_name)> # now this method can be called as classmethod> # print_name() method is called a class method> Student.print_name()> |
>
>산출
The name is : Geeksforgeeks>
클래스 메소드를 사용한 팩토리 메소드
classmethod() 함수의 사용은 객체가 아닌 클래스 이름으로 많은 함수를 호출하려는 팩토리 디자인 패턴에 사용됩니다.
파이썬3
# Python program to demonstrate> # use of a class method and static method.> from> datetime>import> date> class> Person:> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> ># a class method to create a> ># Person object by birth year.> >@classmethod> >def> fromBirthYear(>cls>, name, year):> >return> cls>(name, date.today().year>-> year)> >def> display(>self>):> >print>(>'Name : '>,>self>.name,>'Age : '>,>self>.age)> person>=> Person(>'mayank'>,>21>)> person.display()> |
>
>산출
Name : mayank Age : 21>
상속을 위해 클래스 메소드가 어떻게 작동합니까?
이 예에서는 두 개의 클래스로 Python 클래스 계층 구조를 만듭니다.Person>그리고Man>, 클래스 메서드 및 상속의 사용법을 보여줍니다.
파이썬3
무한 루프
from> datetime>import> date> # random Person> class> Person:> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> >@staticmethod> >def> from_FathersAge(name, fatherAge, fatherPersonAgeDiff):> >return> Person(name, date.today().year>-> fatherAge>+> fatherPersonAgeDiff)> >@classmethod> >def> from_BirthYear(>cls>, name, birthYear):> >return> cls>(name, date.today().year>-> birthYear)> >def> display(>self>):> >print>(>self>.name>+> ''s age is: '> +> str>(>self>.age))> class> Man(Person):> >sex>=> 'Female'> man>=> Man.from_BirthYear(>'John'>,>1985>)> print>(>isinstance>(man, Man))> man1>=> Man.from_FathersAge(>'John'>,>1965>,>20>)> print>(>isinstance>(man1, Man))> |
>
>산출
True False>
Python @classmethod 데코레이터
@classmethod 데코레이터는 내장되어 있습니다. 함수 데코레이터 이는 함수가 정의된 후에 평가되는 표현식입니다. 해당 평가 결과는 함수 정의에 영향을 미칩니다. 클래스 메서드는 인스턴스 메서드가 인스턴스를 받는 것처럼 클래스를 암시적 첫 번째 인수로 받습니다.
클래스메서드 데코레이터의 구문
클래스 C(객체):
@classmethod
def 재미(cls, arg1, arg2, …):
….
어디,
씨
- 재미있는: 클래스 메소드로 변환되어야 하는 함수
- 보고: 함수에 대한 클래스 메소드.
메모:
- 클래스 메소드는 클래스의 객체가 아닌 클래스에 바인딩된 메소드입니다.
- 객체 인스턴스가 아닌 클래스를 가리키는 클래스 매개변수를 사용하므로 클래스 상태에 액세스할 수 있습니다.
- 클래스의 모든 인스턴스에 적용되는 클래스 상태를 수정할 수 있습니다. 예를 들어 모든 인스턴스에 적용할 수 있는 클래스 변수를 수정할 수 있습니다.
예
아래 예에서는 staticmethod() 및 classmethod()를 사용하여 사람이 성인인지 여부를 확인합니다.
파이썬3
# Python program to demonstrate> # use of a class method and static method.> from> datetime>import> date> class> Person:> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> ># a class method to create a> ># Person object by birth year.> >@classmethod> >def> fromBirthYear(>cls>, name, year):> >return> cls>(name, date.today().year>-> year)> ># a static method to check if a> ># Person is adult or not.> >@staticmethod> >def> isAdult(age):> >return> age>>18> person1>=> Person(>'mayank'>,>21>)> person2>=> Person.fromBirthYear(>'mayank'>,>1996>)> print>(person1.age)> print>(person2.age)> # print the result> print>(Person.isAdult(>22>))> |
>
>산출
21 27 True>