>  기사  >  백엔드 개발  >  Python의 클래스 및 유형에 대한 자세한 설명

Python의 클래스 및 유형에 대한 자세한 설명

高洛峰
高洛峰원래의
2017-03-07 16:41:521386검색

클래스란 무엇인가요?

는 카테고리나 타입의 동의어라고 볼 수 있습니다. 모든 객체는 특정 클래스에 속하며 클래스의 인스턴스라고 합니다.

예: Bird는 "bird"의 인스턴스입니다. 이것은 많은 하위 클래스가 있는 일반(추상) 클래스일 뿐입니다. 여러분이 보는 새는 하위 클래스 "종달새"에 속할 수 있습니다. "새"를 모든 새의 집합으로 생각하세요. 그 중 "종달새"가 하위 집합입니다. 객체가 속한 클래스가 다른 객체가 속한 클래스의 하위 집합인 경우 전자를 후자의 하위 클래스라고 하므로 "larks"는 "birds"의 하위 클래스이고 "birds"는 "larks" "Bird"입니다. " 슈퍼클래스

서브클래스 정의는 더 많은 메소드를 정의하는 과정일 뿐입니다

클래스 생성

>>> class Person:
    def setName(self,name):
        self.name=name
    def getName(self):
        return self.name
    def greet(self):
        print "Hello,world! I'm %s" % self.name

        
>>> foo=Person()
>>> bar=Person()
>>> foo.setName('Nsds')
>>> bar.setName('Ysdy')
>>> foo.greet()
Hello,world! I'm Nsds
>>> bar.greet()
Hello,world! I'm Ysdy

foo의 setName 및 Greeting 함수를 호출하면 foo는 자동으로 첫 번째 매개변수로 함수에 자신을 전달하므로 이름이 self로 지정됩니다. self가 없으면 멤버 메서드는 속성을 조작하려는 개체 자체에 액세스할 수 없습니다.

속성은 외부에서 액세스할 수 있습니다.

>>> foo.name
'Nsds'
>>> bar.name='Yoda'
>>> bar.greet()
Hello,world! I'm Yoda

특징, 함수, 메소드

self 매개변수는 실제로 메소드와 함수의 차이입니다. 메소드는 첫 번째 매개변수를 해당 인스턴스에 바인딩하므로 이 매개변수를 제공할 필요가 없습니다. 따라서 속성을 일반 함수에 바인딩할 수 있으므로 특별한 자체 매개변수는 없습니다:

(특성은 객체 내부의 변수이고 객체의 상태는 해당 속성으로 설명되며 객체의 메서드는 특성은 변경될 수 있고, 특성은 객체 외부에서 직접 접근 가능)

>>> class Class:
    def method(self):
        print 'I have a self!'

        
>>> def function():
    print "I don't..."

>>> s=Class()
>>> s.method()
I have a self!
>>> s.method=function
>>> s.method()
I don't...

birdsong 변수는 Bird.sing 바인딩 방법 또는 다음에 대한 액세스를 나타냅니다. self 매개변수(여전히 클래스의 동일한 인스턴스에 바인딩됨)

>>> class Bird:
    song='Squaawk'
    def sing(self):
        print self.song

        
>>> bird=Bird()
>>> bird.sing()
Squaawk
>>> birdsong=bird.sing
>>> birdsong()
Squaawk

이름 앞에 이중 밑줄이 있으면 메서드나 속성이 비공개가 됩니다(에서 액세스할 수 없음). 외부) 액세스)

>>> class Secretive:
    def __inaccessible(self):
        print "Bet you can't see me..."
    def accessible(self):
        print "The secret message is:"
        self.__inaccessible()

        
>>> s=Secretive()
>>> s.__inacessible()

Traceback (most recent call last):
  File "<pyshell#182>", line 1, in <module>
    s.__inacessible()
AttributeError: &#39;Secretive&#39; object has no attribute &#39;__inacessible&#39;
>>> s.accessible()
The secret message is:
Bet you can&#39;t see me...

클래스의 내부 정의에서 이중 밑줄로 시작하는 모든 이름은 단일 밑줄이 앞에 오는 이름으로 "변환"됩니다. 및 클래스 이름 형식

>>> Secretive._Secretive__inaccessible<unbound method Secretive.__inaccessible>
>>> s._Secretive__inaccessible()
Bet you can&#39;t see me...

클래스의 네임스페이스

클래스가 정의되면 클래스 문에 있는 모든 코드가 특수 네임스페이스 - --클래스의 네임스페이스입니다. 이 네임스페이스는 클래스의 모든 멤버가 액세스할 수 있습니다.

클래스의 정의는 실제로 실행 코드 블록입니다.

>>> class MemberCounter:
    members=0
    def init(self):
        MemberCounter.members+=1

        
>>> m1=MemberCounter()
>>> m1.init()
>>> m1.members
>>> m1.members=2
>>> m1.members
>>> m2=MemberCounter()
>>> m2.init()
>>> m2.members
>>> m2.init()
>>> m2.members
>>> m1.members
>>>

새 멤버 값은 특성에 기록됩니다. m1, 클래스 범위 내의 마스크된 변수

superclass

>>> class Filter:
    def init(self):
        self.blocked=[]
    def filter(self,sequence):
        return [x for x in sequence if x not in self.blocked]

    
>>> class SPAMFilter(Filter):
    def init(self):
        self.blocked=[&#39;SPAM&#39;]

        
>>> f=Filter()
>>> f.init()
>>> f.filter([1,2,3])
[1, 2, 3]
>>> s=SPAMFilter()
>>> s.init()
>>> s.filter([&#39;SPAM&#39;,&#39;SPAM&#39;,&#39;egg&#39;,&#39;name&#39;,&#39;ff&#39;])
[&#39;egg&#39;, &#39;name&#39;, &#39;ff&#39;]

상속, 슈퍼클래스

>>> class Filter:
    def init(self):
        self.blockes=[]
    def filter(self,sequence):
        return [x for x in sequence if x not in self.blocked]

    
>>> class S(Filter):
    def init(self):
        self.blocked=[&#39;s&#39;]

        
>>> f=Filter()
>>> f.init()
>>> f.filter([1,2,3])

여러 슈퍼 클래스

먼저 상속된 클래스의 메서드는 나중에 상속된 클래스의 메서드를 재정의합니다.

>>> class C():
    def calculate(self,expression):
        self.value=eval(expression)

        
>>> class Talker():
    def talk(self):
        print 'Hi,my value is',self.value

        
>>> class TalkingCalculator(C,Talker):
    pass

>>> tc=TalkingCalculator()
>>> tc.calculate('1+2*3')
>>> tc.talk()
Hi,my value is 7

파이썬의 클래스와 타입에 대한 자세한 설명과 관련된 더 많은 글은 PHP 중국어 홈페이지를 주목해주세요!

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