레이블이 __인 게시물을 표시합니다. 모든 게시물 표시
레이블이 __인 게시물을 표시합니다. 모든 게시물 표시

2016년 8월 26일 금요일

python 에서 밑줄 ('_', underline) 사용된 파일, 함수, 변수 List 및 그 의미

1. 파일
    폴더 아래의 __init__.py
        해당 폴더가 파이썬 package 라고 인식할 수 있게 한다.
        그 폴더가 package 이기 때문에 그 안에 있는 python 파일들을 import 할 수 있다.

2. 메서드(method, 클래스 내부 함수, 가장 아래 예시 코드)
    1) '_' 이 앞에 붙으면 외부 사용자는 사용하지 말라는 권유의 문법이고,
 a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

    2) '__' 이 앞에 붙으면 private 가 되어 외부에서 사용할 수 없고, 다른 클래스 에서 사용하거나 override 할 수 없다.
 it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

    3) __이름__ : __init__ 함수의 경우는 class 생성 시 자동으로 실행되는 생성자이다.
                  init 외의 __이름__ 는 그냥 함수이며 클래스 외부에서 call 할 수 있다.

3. 속성(Attribute, 클래스 내의 변수)
    위 2.메서드와 동일한 특성을 가진다.
    특별히 class 에서 default로 만들어진 attribute 이 있으며 각 사용법에 맞게 사용된다.
    __name__ : 해당 파일이 실행된 것이면 "__main__" 이 셋팅된다.
    __file__: 해당 파일의 이름
    그 외에도 종류가 있을 것이므로 확인 시 추가 예정


참조 : Link



2-예시 코드

1) 클래스 선언
class TestClass:
    def __init__(self):
        self.a = "a"
    def __dUnderscoreBothSide__(self):
        self.udb = "udb"
    def __dUnderscoreOneSide(self):
        self.udo = "udo"

2) 클래스 인스턴스 생성
t = TestClass()
 
3) attribute a 출력
t.a
'a'
 
4) attribute udb 출력  에러 확인
t.udb
AttributeError                            Traceback (most recent call last)
<ipython-input-4-12af1792c567> in <module>()
----> 1 t.udb
 
AttributeError: 'TestClass' object has no attribute 'udb'

5) attribute udo 출력  에러 확인
t.udo
AttributeError                            Traceback (most recent call last)
<ipython-input-5-89e092a247e5> in <module>()
----> 1 t.udo
 
AttributeError: 'TestClass' object has no attribute 'udo'
 
6) __dUnderscoreBothSide__ method함수 실행 확인 
t.__dUnderscoreBothSide__()
 
7) udb attribute 출력 확인
t.udb
'udb'
 
8) 클래스 외부에서__dUnderscoreOneSide 실행 시 에러 확인
t.__dUnderscoreOneSide()
AttributeError                            Traceback (most recent call last)
<ipython-input-8-58ea9d19081f> in <module>()
----> 1 t.__dUnderscoreOneSide()
 

AttributeError: 'TestClass' object has no attribute '__dUnderscoreOneSide'