Programming

파이썬에서 클래스 메소드 내에서 "정적"클래스 변수에 액세스하는 방법

procodes 2020. 6. 23. 08:03
반응형

파이썬에서 클래스 메소드 내에서 "정적"클래스 변수에 액세스하는 방법


다음과 같은 파이썬 코드가있는 경우 :

class Foo(object):
    bar = 1

    def bah(self):
        print(bar)

f = Foo()
f.bah()

불평

NameError: global name 'bar' is not defined

bar메소드 내에서 클래스 / 정적 변수에 어떻게 액세스 할 수 bah있습니까?


또는 대신 bar사용하십시오 . 에 할당 하면 정적 변수가 생성되고에 할당 하면 인스턴스 변수가 생성됩니다.self.barFoo.barFoo.barself.bar


클래스 메소드를 정의하십시오.

class Foo(object):
    bar = 1
    @classmethod
    def bah(cls):    
        print cls.bar

이제 bah()인스턴스 메소드 여야하는 경우 (즉, 자체에 액세스 할 수있는 경우) 클래스 변수에 직접 액세스 할 수 있습니다.

class Foo(object):
    bar = 1
    def bah(self):    
        print self.bar

모든 좋은 예와 마찬가지로 실제로 수행하려는 작업을 단순화했습니다. 이것은 좋지만 파이썬이 클래스 변수와 인스턴스 변수에 관해서 많은 유연성을 가지고 있음을 주목할 가치가 있습니다. 방법에 대해서도 마찬가지입니다. 좋은 가능성 목록을 보려면 Michael Fötsch의 새로운 스타일의 수업 소개 , 특히 섹션 2-6을 읽는 것이 좋습니다 .

시작할 때 기억해야 할 많은 작업 중 하나는 파이썬이 자바가 아니라는 것입니다. 진부한 것 이상. Java에서는 전체 클래스가 컴파일되어 네임 스페이스 확인이 단순 해집니다. 메소드 외부 (어디서나) 외부에 선언 된 모든 변수는 인스턴스 (또는 정적 인 경우) 변수이며 메소드 내에서 암시 적으로 액세스 할 수 있습니다.

파이썬에서 가장 중요한 규칙은 변수에 대해 순서대로 검색되는 세 개의 네임 스페이스가 있다는 것입니다.

  1. 기능 / 방법
  2. 현재 모듈
  3. 내장

{begin pedagogy}

이에 대한 제한된 예외가 있습니다. 나에게 발생하는 주요한 것은 클래스 정의가로드 될 때 클래스 정의가 자체 암시 적 네임 스페이스라는 것입니다. 그러나 이것은 모듈이로드되는 동안에 만 지속되며 메소드 내에서 완전히 우회됩니다. 그러므로:

>>> class A(object):
        foo = 'foo'
        bar = foo


>>> A.foo
'foo'
>>> A.bar
'foo'

그러나:

>>> class B(object):
        foo = 'foo'
        def get_foo():
            return foo
        bar = get_foo()



Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    class B(object):
  File "<pyshell#11>", line 5, in B
    bar = get_foo()
  File "<pyshell#11>", line 4, in get_foo
    return foo
NameError: global name 'foo' is not defined

{end pedagogy}

In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.


class Foo(object):
     bar = 1
     def bah(self):
         print Foo.bar

f = Foo() 
f.bah()

class Foo(object) :

          bar = 1

          def bah(object_reference) :

                 object_reference.var=Foo.bar

                 return object_reference.var

f = Foo() 

print 'var=', f.bah()

참고URL : https://stackoverflow.com/questions/707380/in-python-how-can-i-access-static-class-variables-within-class-methods

반응형