강좌
클라우드/리눅스에 관한 강좌입니다.
프로그램 분류

파이썬기초46 : 정적메서드와 클래스메서드

작성자 정보

  • 관리자 작성
  • 작성일

컨텐츠 정보

본문

#정적메서드.py

# 정적메서드(static method)는 클래스 인스턴스에 전혀 작용하지 않는 메서드를 의미한다. 

# 클래스메서드(class method)는 인스턴스가 아니라 클래스 자체에 작용하는 메서드이다. 

# “클래스명.메서드명”으로 호출할 수 있다.

# "클래스명.메서드명" 으로 직접호출할 수 있다. 


class MyCalc(object):

    @staticmethod

    def my_add(x,y):

        return x+y


#클래스에서 직접 호출한다.

a = MyCalc.my_add(5,7)

print(a)



# @classmethod라는 데코레이터를 사용한다.

# @classmethod라는 데코레이터를 사용하여 static method를 정의한다.

class CoeffVar(object):

    coefficient = 1 

    @classmethod

    def mul(cls, fact): # cls라는 첫번째 인자는 클래스 자체

        return cls.coefficient * fact


#파생형식을 정의

class MulFive(CoeffVar):

    coefficient = 5


x = MulFive.mul(4)

print(x)

20



#두번째 예제는 인스턴스 생성 방법을 하나 이상 정의한 데모코드이다. 

import time 

class MyTime(object):

    def __init__(self, hour, minutes, sec):

        self.hour = hour 

        self.minutes = minutes

        self.sec = sec 


    @staticmethod

    def now():

        t = time.localtime()

        return MyTime(t.tm_hour, t.tm_min, t.tm_sec)

    @staticmethod

    def two_hours_later():

        t = time.localtime(time.time()+7200)

        return MyTime(t.tm_hour, t.tm_min, t.tm_sec)


#아래와 같이 다양한 방법으로 호출할 수 있다. 

a = MyTime(15, 30, 40)

b = MyTime.now()

c = MyTime.two_hours_later()

print("a {0}:{1}:{2}".format(a.hour, a.minutes, a.sec))

print("b {0}:{1}:{2}".format(b.hour, b.minutes, b.sec))

print("c {0}:{1}:{2}".format(c.hour, c.minutes, c.sec))

관련자료

댓글 0
등록된 댓글이 없습니다.

공지사항


뉴스광장


  • 현재 회원수 :  60,037 명
  • 현재 강좌수 :  35,810 개
  • 현재 접속자 :  90 명