자식 클래스에 부모 클래스의 메서드와 이름이 같은 메서드가있는 경우 자식 클래스의 메서드가 부모 클래스의 메서드를 재정의합니다.
자식 클래스 정의에서 부모 클래스의 메서드는 super()
.
그러면 자식 클래스 Instance에서 부모 클래스의 메서드에 액세스 할 수 있습니까?
class Person:
def print(self):
print("Message from Person")
class Student(Person):
def print(self):
print("Message from Student")\
s = Student()
# Method of Student Class Instance
s.print() # Output: "Message from Student"
# I want to call method "print" of Person
# from student Instance
# How can I call it?
s.super().print() # ERROR
super(s).print() # ERROR
다른 방법으로 부모 클래스에 액세스 할 수있는 방법이 전혀 없다면 그렇게 할 수있을 것 같지만 절대 권장 하지 않습니다 .
class Person:
def print(self):
print("Message from Person")
class Student(Person):
def print(self):
print("Message from Student")
s = Student()
# Method of Student Class Instance
s.print() # Output: "Message from Student"
s.__class__.__base__.print(s.__class__.__base__) # Output: "Message from Person"
이 슈퍼 해키 것을 이해해야하고, 그것의 경우와 같이 사용하면, 인스턴스의 메소드를 호출하지 않는 것이 s.print()
아니라있는 방법,하지만 당신은는 uninstantiated 클래스의 메소드를 호출하는 classmethod
(또는 staticmethod
그것을 위해를 문제) 클래스에 인수 (즉, self
인수)로 전달합니다. 매우 다른 구문입니다.
다시 말하지만, 메서드를 재정의하는 대신 다른 이름을 지정하는 것이 훨씬 더 합리적입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다