문제

을 만들 때에는 간단한 개체 계층구조에서 Python,고 싶을 호출 할 수 있는 방법의 부모 등에서 파생된 클래스입니다.Perl Java,키워드에 대한 이(super).In Perl,I 에 이 기능을 사용할 수 있습니다:

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

sub frotz {
   my $str = SUPER::frotz();
   return uc($str);
}

파이썬에서,그것은이 나타나는 내가 이 부모 클래스에서 명시적으로습니다.위의 예에서 나는 뭔가 Foo::frotz().

이 바로 보이지 않는,때문에 이 행동하기가 어렵게 깊은 계층 구조입니다.는 경우 아이들이 알아야 할 무엇 클래스 정의된 상속된 방법에서,모든 종류의 정보를 고통이 만들어집니다.

이는 실제 제한 python,틈에서 나의 이해하나요?

도움이 되었습니까?

해결책

예,하지만 새로운 스타일의 수업. 사용 super() 기능:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

Python 3.x의 경우 다음을 사용할 수 있습니다.

class Foo(Bar):
    def baz(self, arg):
        return super().baz(arg)

다른 팁

파이썬도 가지고 있습니다 감독자 또한:

감독자(type[, object-or-type])

메소드 호출을 부모 또는 형제 클래스의 유형에 위임하는 프록시 개체를 반환합니다. 이는 클래스에서 무시 된 상속 된 메소드에 액세스하는 데 유용합니다. 검색 순서는 유형 자체가 건너 뜁니다.

예시:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()
ImmediateParentClass.frotz(self)

직계 상위 클래스가 정의되었는지 여부에 관계없이 괜찮을 것입니다. frotz 그 자체로 물려 받았습니다. super 적절한 지원에만 필요합니다 다수의 상속 (그리고 모든 클래스가 올바르게 사용하는 경우에만 작동합니다). 일반적으로 AnyClass.whatever 찾아 볼 것입니다 whatever 안에 AnyClass의 조상 AnyClass 그것을 정의/재정의하지 않으며, 이것은 다른 사건과 같이 "Child Class Calling Parent 's Method"에 적용됩니다!

파이썬 3 부모 메소드를 호출하기위한 다르고 간단한 구문이 있습니다.

만약에 Foo 클래스는 Bar, 그 다음 Bar.__init__ 호출 할 수 있습니다 Foo ~을 통해 super().__init__():

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

많은 답변이 자녀에게 무시 된 부모의 방법을 호출하는 방법을 설명했습니다.

하지만

"아동 수업에서 부모 수업의 방법을 어떻게 호출합니까?"

또한 의미 할 수 있습니다.

"상속 된 방법을 어떻게 호출합니까?"

교도소가 덮어 쓰지 않은 한 마치 아동 수업의 방법 인 것처럼 부모 수업에서 상속 된 방법을 호출 할 수 있습니다.

예 : Python 3에서 :

class A():
  def bar(self, string):
    print("Hi, I'm bar, inherited from A"+string)

class B(A):
  def baz(self):
    self.bar(" - called by baz in B")

B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"

그렇습니다. 이것은 상당히 분명 할 수 있지만, 나는 이것을 지적하지 않으면 사람들 이이 실을 인상으로 떠날 수 있다고 생각합니다. 당신은 파이썬에서 상속 된 방법에 액세스하기 위해 말도 안되는 후프를 뛰어 넘어야한다고 생각합니다. 특히이 질문은 "Python에서 상위 클래스의 방법에 액세스하는 방법"을 검색하는 데있어 높은 비율로, OP는 Python에 새로운 사람의 관점에서 작성됩니다.

나는 찾았다 :https://docs.python.org/3/tutorial/classes.html#inheritance상속 된 방법에 액세스하는 방법을 이해하는 데 유용합니다.

다음은 사용의 예입니다 감독자():

#New-style classes inherit from object, or from another new-style class
class Dog(object):

    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self):
        self.moves.append('walk')
        self.moves.append('run')

    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super(Superdog, self).moves_setup()
        self.moves.append('fly')

dog = Superdog('Freddy')
print dog.name # Freddy
dog.moves_setup()
print dog.get_moves() # ['walk', 'run', 'fly']. 
#As you can see our Superdog has all moves defined in the base Dog class

파이썬에는 슈퍼 ()도 있습니다. Python의 구식 및 새 스타일 클래스 때문에 약간 원래이지만 생성자에는 일반적으로 사용됩니다.

class Foo(Bar):
    def __init__(self):
        super(Foo, self).__init__()
        self.baz = 5

사용하는 것이 좋습니다 CLASS.__bases__이 같은

class A:
   def __init__(self):
        print "I am Class %s"%self.__class__.__name__
        for parentClass in self.__class__.__bases__:
              print "   I am inherited from:",parentClass.__name__
              #parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()

당신이 얼마나 많은 논쟁을받을 수 있는지 모르고, 그들 모두를 자녀에게 전달하고 싶다면 :

class Foo(bar)
    def baz(self, arg, *args, **kwargs):
        # ... Do your thing
        return super(Foo, self).baz(arg, *args, **kwargs)

(에서: Python -Super () 호출 후 옵션 Kwarg를 사용해야하는 경우 __init__를 재정의하는 가장 깨끗한 방법?)

슈퍼()에서 python 한다.

예제는 방법에 대한 수퍼 클래스 메소드가 호출에 하위 클래스 메소드

class Dog(object):
    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self,x):
        self.moves.append('walk')
        self.moves.append('run')
        self.moves.append(x)
    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super().moves_setup("hello world")
        self.moves.append('fly')
dog = Superdog('Freddy')
print (dog.name)
dog.moves_setup()
print (dog.get_moves()) 

이 예제는 이와 유사한 설명했다.그러나 거기에 하나의 차이는 최고 없이 모든 인수로 전달됩니다.이는 위의 코드는 실행 파일에서는 파이썬 3.4 버전입니다.

Python 2에서는 Super ()에 많은 운이 없었습니다. 나는 jimifiki의 답을 이것에 사용했습니다. Python에서 부모 방법을 참조하는 방법은 무엇입니까?. 그런 다음 내 자신의 작은 비틀기를 추가했습니다. 이는 유용성이 향상된다고 생각합니다 (특히 클래스 이름이 긴 경우).

하나의 모듈에서 기본 클래스를 정의하십시오.

 # myA.py

class A():     
    def foo( self ):
        print "foo"

그런 다음 클래스를 다른 모듈로 가져옵니다 as parent:

# myB.py

from myA import A as parent

class B( parent ):
    def foo( self ):
        parent.foo( self )   # calls 'A.foo()'

이 예에서 CAFEC_PARAM은 기본 클래스 (부모 수업)이고 ABC는 어린이 수업입니다. ABC는 기본 클래스에서 AWC 메소드를 호출합니다.

class cafec_param:

    def __init__(self,precip,pe,awc,nmonths):

        self.precip = precip
        self.pe = pe
        self.awc = awc
        self.nmonths = nmonths

    def AWC(self):

        if self.awc<254:
            Ss = self.awc
            Su = 0
            self.Ss=Ss
        else:
            Ss = 254; Su = self.awc-254
            self.Ss=Ss + Su   
        AWC = Ss + Su
        return self.Ss
         

    def test(self):
        return self.Ss
        #return self.Ss*4

class abc(cafec_param):
    def rr(self):
        return self.AWC()


ee=cafec_param('re',34,56,2)
dd=abc('re',34,56,2)
print(dd.rr())
print(ee.AWC())
print(ee.test())

산출

56

56

56

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()
class a(object):
    def my_hello(self):
        print "hello ravi"

class b(a):
    def my_hello(self):
    super(b,self).my_hello()
    print "hi"

obj = b()
obj.my_hello()

이것은 더 추상적 인 방법입니다.

super(self.__class__,self).baz(arg)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top