수색…


기본 다형성

다형성 (Polymorphism)은 객체의 유형에 관계없이 객체에 대한 작업을 수행하는 기능입니다. 이것은 일반적으로 기본 클래스를 작성하고 모두 동일한 서명으로 메소드를 구현하는 두 개 이상의 서브 클래스를 사용하여 구현됩니다. 이러한 객체를 조작하는 다른 모든 함수 또는 메소드는 먼저 유형 검사를 수행 할 필요없이 조작중인 객체의 유형에 관계없이 동일한 메소드를 호출 할 수 있습니다. 클래스 X가 클래스 Y를 확장 할 때 객체 지향 용어에서 Y는 수퍼 클래스 또는 기본 클래스라고하며 X는 서브 클래스 또는 파생 클래스라고합니다.

class Shape:
    """
    This is a parent class that is intended to be inherited by other classes
    """

    def calculate_area(self):
        """
        This method is intended to be overridden in subclasses.
        If a subclass doesn't implement it but it is called, NotImplemented will be raised.

        """
        raise NotImplemented

class Square(Shape):
    """
    This is a subclass of the Shape class, and represents a square
    """
    side_length = 2     # in this example, the sides are 2 units long

    def calculate_area(self):
        """
        This method overrides Shape.calculate_area(). When an object of type
        Square has its calculate_area() method called, this is the method that
        will be called, rather than the parent class' version.

        It performs the calculation necessary for this shape, a square, and
        returns the result.
        """
        return self.side_length * 2

class Triangle(Shape):
    """
    This is also a subclass of the Shape class, and it represents a triangle
    """
    base_length = 4
    height = 3

    def calculate_area(self):
        """
        This method also overrides Shape.calculate_area() and performs the area
        calculation for a triangle, returning the result.
        """

        return 0.5 * self.base_length * self.height

def get_area(input_obj):
    """
    This function accepts an input object, and will call that object's
    calculate_area() method. Note that the object type is not specified. It
    could be a Square, Triangle, or Shape object.
    """

    print(input_obj.calculate_area())

# Create one object of each class
shape_obj = Shape()
square_obj = Square()
triangle_obj = Triangle()

# Now pass each object, one at a time, to the get_area() function and see the
# result.
get_area(shape_obj)
get_area(square_obj)
get_area(triangle_obj)

우리는이 결과를보아야한다.

없음
4
6.0

다형성이 없으면 어떻게됩니까?
다형성이 없으면 호출 할 올바른 메서드를 결정하기 위해 개체에 대한 작업을 수행하기 전에 형식 검사가 필요할 수 있습니다. 다음 카운터 예제 는 이전 코드와 동일한 작업을 수행하지만 다형성을 사용하지 않으면 get_area() 함수가 더 많은 작업을 수행해야합니다.

class Square:

    side_length = 2

    def calculate_square_area(self):
        return self.side_length ** 2

class Triangle:

    base_length = 4
    height = 3

    def calculate_triangle_area(self):
        return (0.5 * self.base_length) * self.height

def get_area(input_obj):

    # Notice the type checks that are now necessary here. These type checks
    # could get very complicated for a more complex example, resulting in
    # duplicate and difficult to maintain code.

    if type(input_obj).__name__ == "Square":
        area = input_obj.calculate_square_area()

    elif type(input_obj).__name__ == "Triangle":
        area = input_obj.calculate_triangle_area()

    print(area)

# Create one object of each class
square_obj = Square()
triangle_obj = Triangle()

# Now pass each object, one at a time, to the get_area() function and see the
# result.
get_area(square_obj)
get_area(triangle_obj)

우리는이 결과를보아야한다.

4
6.0

중요 사항
카운터 예제에서 사용 된 클래스는 "새로운 스타일"클래스이며 Python 3이 사용되는 경우에는 객체 클래스에서 암시 적으로 상속받습니다. 다형성은 Python 2.x와 3.x에서 모두 작동하지만, 다형성 반례 코드는 type (input_obj) 때문에 Python 2.x 인터프리터에서 실행될 경우 예외를 발생시킵니다. name 은 객체에서 명시 적으로 상속되지 않으면 클래스 이름 대신 "instance"를 반환하므로 할당되지 않은 영역이됩니다.

오리 타이핑

다이나믹 타이핑 시스템으로 인해 Python에서 사용할 수있는 오리 타이핑의 형태로 상속이없는 다형성. 즉, 클래스가 동일한 메소드를 포함하고있는 한 Python 인터프리터는 호출을 호출 할 때만 런타임에 발생하므로이를 구분하지 않습니다.

class Duck:
    def quack(self):
        print("Quaaaaaack!")
    def feathers(self):
        print("The duck has white and gray feathers.")

class Person:
    def quack(self):
        print("The person imitates a duck.")
    def feathers(self):
        print("The person takes a feather from the ground and shows it.")
    def name(self):
        print("John Smith")

def in_the_forest(obj):
    obj.quack()
    obj.feathers()

donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)

출력은 다음과 같습니다.

퀴어팩!
오리는 흰색과 회색 깃털을 가지고 있습니다.
그 사람은 오리를 흉내 낸다.
그 사람은 땅에서 깃털을 가져 와서 그것을 보여준다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow