[Python] class에 속한 객체의 수 구하는 법

조회수 1904회

제목 그대로 입니다.

class MyCounter:
    def __init__(self, value=0):
        self.counter = value
        pass
    def number_of_counters():
        return ~~~~

c1 = MyCounter()
print(MyCounter.number_of_counters())
c2 = MyCounter(1)
print(MyCounter.number_of_counters())
c3 = MyCounter(2)
print(MyCounter.number_of_counters())

위와 같은 코드에서

1
2
3

의 결과를 얻으려면 어떤 방법을 써야할까요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • 음 작성한 코드를 보니 공부를 많이 해야 할 듯 합니다.

    인스턴스 변수, 클래스 변수 차이부터 학습해보시기 바랍니다.

    • 인스턴스 변수인 경우
    class MyCounter:
        def __init__(self, value=0):
            self.counter = value + 1
            pass
        def number_of_counters(self):
            return self.counter
    
    c1 = MyCounter()
    print(c1.number_of_counters())
    c2 = MyCounter(1)
    print(c2.number_of_counters())
    c3 = MyCounter(2)
    print(c3.number_of_counters())
    
    1
    2
    3
    
    • 클래스 변수인 경우
    class MyCounter:
        counter = 0
        def __init__(self, value=0):
            MyCounter.counter = value + 1
            pass
        def number_of_counters():
            return MyCounter.counter
    
    c1 = MyCounter()
    print(MyCounter.number_of_counters())
    c2 = MyCounter(1)
    print(MyCounter.number_of_counters())
    c3 = MyCounter(2)
    print(MyCounter.number_of_counters())
    
    1
    2
    3
    
  • 질문의 의미가 정확히 이해가 안되지만, 코드 상에서 특정 클래스에 의해 만들어진 객체의 수를 확인하는 방법으로 이해한다면, 아래 두번째 코드에 return cnt를 첨가해 `def number_of_counters(self)에 넣으면 될 것 같은데요...

    class A():
        pass
    
    a = A()
    b = A()
    c = A()
    
    cnt = 0
    for n in range(len(dir())):
        if isinstance(eval("%s" %dir()[n]),A(클래스이름)): cnt = cnt + 1
    
    >>> cnt
    3
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)