>  기사  >  백엔드 개발  >  Python 객체 지향 액세스 제한

Python 객체 지향 액세스 제한

不言
不言원래의
2018-04-14 10:21:251712검색

이 글에서 공유한 내용은 Python 객체 지향 접근 제한 사항입니다. 특정 참조 값이 있으므로 필요한 친구가 참조할 수 있습니다.

클래스 내부에는 속성과 메서드가 있을 수 있으며, 외부 코드는 직접 사용할 수 있습니다. 인스턴스 변수에 의해 호출되는 메소드는 데이터를 조작하는 데 사용되므로 복잡한 내부 논리를 숨깁니다.

그러나 Student 클래스의 이전 정의에 따르면 외부 코드는 여전히 인스턴스의 이름 및 점수 속성을 자유롭게 수정할 수 있습니다.

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print('%s:%s'%(self.name,self.score))
    def get_grade(self):
        if self.score >=90:
            return 'A'
        elif self.score>=600:
            return  'B'
        else:
            return  'C'
bart = Student('Boyuan Zhou',100)
print(bart.score)
bart.score=120
print(bart.score)
100
120

내부 속성이 외부에서 액세스되는 것을 방지하려면 속성 이름 앞에 밑줄 __. Python에서 인스턴스의 변수 이름이 __로 시작하면 내부에서만 액세스할 수 있고 외부에서는 액세스할 수 없는 프라이빗 속성이 됩니다. 학생 수업:

class Student(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def print_score(self):
        print('%s:%s'%(self.__name,self.__score))
    def get_grade(self):
        if self.__score >=90:
            return 'A'
        elif self.__score>=600:
            return  'B'
        else:
            return  'C'
改完后,对于外部代码来说,没什么变动,但是已经无法从外部访问实例变量.__name和实例变量.__score了:
bart = Student('Boyuan Zhou',100)
print(bart.__name)Traceback (most recent call last):
  File "F:/mycompany/mycompany/schooldemo.py", line 16, in <module>
    print(bart.__name)
AttributeError: &#39;Student&#39; object has no attribute &#39;__name&#39;

이는 외부 코드가 객체의 내부 상태를 마음대로 수정할 수 없도록 보장하므로 액세스 제한 보호를 통해 코드가 더욱 강력해집니다.

하지만 외부 코드가 이름과 점수를 얻으려면 어떻게 해야 할까요? Student 클래스에 get_name 및 get_score와 같은 메소드를 추가할 수 있습니다.

class Student(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
    
bart = Student(&#39;Boyuan Zhou&#39;,100)
print(bart.get_name())
#Boyuan Zhou

외부 코드에서 점수를 수정할 수 있도록 하려면 어떻게 해야 할까요? Student 클래스에 set_score 메소드를 추가할 수 있습니다:

class Student(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def get_name(self):
        return self.__name    def get_score(self):
        return self.__score
    def set_score(self,score):
        self.__score=score

원래 메소드는 bart.score = 59를 통해 직접 수정할 수 있습니다. 메소드를 정의하는 데 왜 그렇게 많은 어려움을 겪나요? 메서드에서 매개변수를 확인하여 잘못된 매개변수 전달을 피할 수 있기 때문입니다.

class Student(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
    def set_score(self,score):
        if 0 <=score <= 100:
            self.__score=score
        else:
            raise ValueError(&#39;bad score&#39;)

Python에서 변수 이름은 __xxx___와 유사합니다. 즉, 이중 밑줄로 시작하고 이중 밑줄로 끝납니다. 마지막은 특수 변수입니다. 특수 변수는 직접 접근이 가능하며 전용 변수가 아닙니다. 따라서 __name__, __score__ 등의 변수 이름은 사용할 수 없습니다.

때때로 _name과 같이 밑줄로 시작하는 인스턴스 변수가 표시되는 경우가 있습니다. 이러한 인스턴스 변수는 외부에서 액세스할 수 있지만 관례에 따르면 이러한 변수는 '내가 그럴 수도 있지만'이라는 뜻입니다.

이중 밑줄로 시작하는 인스턴스 변수는 반드시 외부에서 접근이 불가능한 것인가요? 사실은 그렇지 않습니다. __name을 직접 접근할 수 없는 이유 Python 인터프리터가 외부에서 __name 변수를 _Student__name으로 변경했으므로 _Student_name을 통해 __name 변수에 계속 액세스할 수 있습니다.

class Student(object):
    def __init__(self,name,score):
        self.__name = name
        self.__score = score
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
    def set_score(self,score):
        if 0 <=score <= 100:
            self.__score=score
        else:
            raise ValueError(&#39;bad score&#39;)
bart = Student('Boyuan Zhou',100)print(bart._Student__name)
print(bart.get_name())
#Boyuan Zhou
#Boyuan Zhou

그러나 이렇게 하지 않는 것이 좋습니다. Python 인터프리터의 버전에 따라 __name이 다른 변수 이름으로 바뀔 수 있기 때문입니다. .

위 내용은 Python 객체 지향 액세스 제한의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.