Phương thức kế thừa trong Python là gì?

Như câu trả lời khác chứng minh cho các lớp đơn giản, chữ ký của một phương thức kế thừa bị ghi đè có thể khác ở con so với ở cha mẹ

Show

Điều này cũng đúng ngay cả khi cha mẹ là một lớp cơ sở trừu tượng

import abc

class Foo:
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def bar(self, x, y):
        return x + y

class ChildFoo(Foo):
    def bar(self, x):
        return super(self.__class__, self).bar(x, 3)

class DumbFoo(Foo):
    def bar(self):
        return "derp derp derp"

cf = ChildFoo()
print cf.bar(5)

df = DumbFoo()
print df.bar()

Đường vòng phức tạp không phù hợp

Đây là một bài tập thú vị trong siêu dữ liệu Python để cố gắng hạn chế khả năng ghi đè các phương thức, sao cho chữ ký đối số của chúng phải khớp với chữ ký của lớp cơ sở. Đây là một nỗ lực

Ghi chú. Tôi không tán thành đây là một ý tưởng kỹ thuật tốt và tôi đã không dành thời gian để giải quyết các vấn đề còn lỏng lẻo nên có thể có một số lưu ý nhỏ về đoạn mã bên dưới có thể làm cho nó hiệu quả hơn hoặc điều gì đó tương tự

import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)

Lưu ý, giống như hầu hết các ý tưởng loại "nghiêm ngặt" hoặc "riêng tư" trong Python, rằng bạn vẫn có thể tự do thực hiện các hàm khỉ vá trên ngay cả một "lớp tốt" và các hàm khỉ vá đó không phải đáp ứng ràng buộc chữ ký

# Instance level
gc = GoodChild()
gc.foo = lambda self=gc: "Haha, I changed the signature!"

# Class level
GoodChild.foo = lambda self: "Haha, I changed the signature!"

và ngay cả khi bạn thêm độ phức tạp hơn vào lớp meta kiểm tra bất cứ khi nào có bất kỳ thuộc tính loại phương thức nào được cập nhật trong lớp

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
9 của lớp và tiếp tục đưa ra câu lệnh
class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
0 khi lớp được sửa đổi, bạn vẫn có thể sử dụng
class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
1 để bỏ qua hành vi tùy chỉnh và thiết lập một thuộc tính.

Trong những trường hợp này, tôi tưởng tượng Jeff Goldblum trong vai Ian Malcolm trong Công viên kỷ Jura, ngây người nhìn bạn và nói "Người lớn đồng ý, uhh, hãy tìm cách. "

Không có ngôn ngữ lập trình hướng đối tượng nào đáng để xem xét hoặc sử dụng nếu nó không hỗ trợ tính kế thừa. Kế thừa được phát minh vào năm 1969 cho Simula. Python không chỉ hỗ trợ kế thừa mà còn hỗ trợ đa kế thừa. Nói chung, kế thừa là cơ chế tạo ra các lớp mới từ các lớp hiện có. Bằng cách này, chúng ta có được một hệ thống phân cấp các lớp. Trong hầu hết các ngôn ngữ hướng đối tượng dựa trên lớp, một đối tượng được tạo thông qua kế thừa (một "đối tượng con") có được tất cả - mặc dù có một số ngoại lệ trong một số ngôn ngữ lập trình - thuộc tính và hành vi của đối tượng cha

Phương thức kế thừa trong Python là gì?

Kế thừa cho phép lập trình viên tạo các lớp được xây dựng dựa trên các lớp hiện có và điều này cho phép một lớp được tạo thông qua kế thừa kế thừa các thuộc tính và phương thức của lớp cha. Điều này có nghĩa là tính kế thừa hỗ trợ khả năng sử dụng lại mã. Các phương thức hay nói chung là phần mềm được kế thừa bởi một lớp con được coi là được sử dụng lại trong lớp con. Mối quan hệ của các đối tượng hoặc các lớp thông qua kế thừa tạo ra một đồ thị có hướng

Lớp mà một lớp kế thừa được gọi là lớp cha hoặc lớp cha. Một lớp kế thừa từ một lớp cha được gọi là một lớp con, còn được gọi là lớp kế thừa hoặc lớp con. Các siêu lớp đôi khi cũng được gọi là tổ tiên. Tồn tại mối quan hệ thứ bậc giữa các lớp. Nó tương tự như các mối quan hệ hoặc phân loại mà chúng ta biết từ cuộc sống thực. Ví dụ, hãy nghĩ về phương tiện. Xe đạp, ô tô, xe buýt và xe tải là phương tiện. Xe bán tải, xe tải, xe thể thao, xe mui trần và xe bất động sản đều là xe ô tô và với tư cách là ô tô, chúng cũng là phương tiện. Chúng tôi có thể triển khai một lớp phương tiện trong Python, lớp này có thể có các phương thức như tăng tốc và phanh. Ô tô, Xe buýt và Xe tải và Xe đạp có thể được triển khai dưới dạng các lớp con sẽ kế thừa các phương thức này từ phương tiện

Phương thức kế thừa trong Python là gì?

Đào tạo Python trực tiếp

Phương thức kế thừa trong Python là gì?

Thưởng thức trang này?

Nhìn thấy. Tổng quan về các khóa học Python trực tiếp

đăng ký tại đây

Cú pháp kế thừa trong Python

Cú pháp cho một định nghĩa lớp con trông như thế này

class DerivedClassName(BaseClassName):
    pass

Thay vì câu lệnh

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
9 sẽ có các phương thức và thuộc tính như ở các lớp khác. Tên BaseClassName phải được xác định trong phạm vi chứa định nghĩa lớp dẫn xuất

Bây giờ chúng ta đã sẵn sàng cho một ví dụ kế thừa đơn giản với mã Python

Ví dụ kế thừa đơn giản

Chúng tôi sẽ gắn bó với các rô-bốt yêu quý của chúng tôi hoặc tốt hơn là lớp

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
0 từ các chương trước của hướng dẫn Python của chúng tôi để chỉ ra nguyên tắc kế thừa hoạt động như thế nào. Chúng tôi sẽ định nghĩa một lớp
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1, kế thừa từ
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
0

________số 8

ĐẦU RA

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James

Phương thức kế thừa trong Python là gì?

Nếu bạn nhìn vào mã của lớp

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1 của chúng tôi, bạn có thể thấy rằng chúng tôi chưa định nghĩa bất kỳ thuộc tính hoặc phương thức nào trong lớp này. Vì lớp
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1 là một lớp con của
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
0, trong trường hợp này, nó kế thừa cả phương thức
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
6 và
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
7. Kế thừa các phương thức này có nghĩa là chúng ta có thể sử dụng chúng như thể chúng đã được định nghĩa trong lớp
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1. Khi chúng ta tạo một thể hiện của
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1, hàm
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
6 cũng sẽ tạo một thuộc tính name. Chúng ta có thể áp dụng phương thức
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
7 cho đối tượng
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
92
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
93, như chúng ta có thể thấy trong kết quả từ đoạn mã trên

Đào tạo Python trực tiếp

Phương thức kế thừa trong Python là gì?

Thưởng thức trang này?

Nhìn thấy. Tổng quan về các khóa học Python trực tiếp

Các khóa học trực tuyến sắp tới

Khóa học nâng cao chuyên sâu

Lập trình hướng đối tượng với Python

đăng ký tại đây

Sự khác biệt giữa import types import inspect def strict(func): """Add some info for functions having strict signature. """ arg_sig = inspect.getargspec(func) func.is_strict = True func.arg_signature = arg_sig return func class StrictSignature(type): def __new__(cls, name, bases, attrs): func_types = (types.MethodType,) # include types.FunctionType? # Check each attribute in the class being created. for attr_name, attr_value in attrs.iteritems(): if isinstance(attr_value, func_types): # Check every base for @strict functions. for base in bases: base_attr = base.__dict__.get(attr_name) base_attr_is_function = isinstance(base_attr, func_types) base_attr_is_strict = hasattr(base_attr, "is_strict") # Assert that inspected signatures match. if base_attr_is_function and base_attr_is_strict: assert (inspect.getargspec(attr_value) == base_attr.arg_signature) # If everything passed, create the class. return super(StrictSignature, cls).__new__(cls, name, bases, attrs) # Make a base class to try out strictness class Base: __metaclass__ = StrictSignature @strict def foo(self, a, b, c="blah"): return a + b + len(c) def bar(self, x, y, z): return x ##### # Now try to make some classes inheriting from Base. ##### class GoodChild(Base): # Was declared strict, better match the signature. def foo(self, a, b, c="blah"): return c # Was never declared as strict, so no rules! def bar(im_a_little, teapot): return teapot/2 # These below can't even be created. Uncomment and try to run the file # and see. It's not just that you can't instantiate them, you can't # even get the *class object* defined at class creation time. # #class WrongChild(Base): # def foo(self, a): # return super(self.__class__, self).foo(a, 5) # #class BadChild(Base): # def foo(self, a, b, c="halb"): # return super(self.__class__, self).foo(a, b, c) 94 và import types import inspect def strict(func): """Add some info for functions having strict signature. """ arg_sig = inspect.getargspec(func) func.is_strict = True func.arg_signature = arg_sig return func class StrictSignature(type): def __new__(cls, name, bases, attrs): func_types = (types.MethodType,) # include types.FunctionType? # Check each attribute in the class being created. for attr_name, attr_value in attrs.iteritems(): if isinstance(attr_value, func_types): # Check every base for @strict functions. for base in bases: base_attr = base.__dict__.get(attr_name) base_attr_is_function = isinstance(base_attr, func_types) base_attr_is_strict = hasattr(base_attr, "is_strict") # Assert that inspected signatures match. if base_attr_is_function and base_attr_is_strict: assert (inspect.getargspec(attr_value) == base_attr.arg_signature) # If everything passed, create the class. return super(StrictSignature, cls).__new__(cls, name, bases, attrs) # Make a base class to try out strictness class Base: __metaclass__ = StrictSignature @strict def foo(self, a, b, c="blah"): return a + b + len(c) def bar(self, x, y, z): return x ##### # Now try to make some classes inheriting from Base. ##### class GoodChild(Base): # Was declared strict, better match the signature. def foo(self, a, b, c="blah"): return c # Was never declared as strict, so no rules! def bar(im_a_little, teapot): return teapot/2 # These below can't even be created. Uncomment and try to run the file # and see. It's not just that you can't instantiate them, you can't # even get the *class object* defined at class creation time. # #class WrongChild(Base): # def foo(self, a): # return super(self.__class__, self).foo(a, 5) # #class BadChild(Base): # def foo(self, a, b, c="halb"): # return super(self.__class__, self).foo(a, b, c) 95

Bạn cũng nên chú ý đến các sự kiện sau, mà chúng tôi cũng đã chỉ ra trong các phần khác của hướng dẫn Python của chúng tôi. Mọi người thường hỏi sự khác biệt giữa việc kiểm tra loại thông qua chức năng

import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
94 hoặc chức năng
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
95 nằm ở đâu. Sự khác biệt có thể được nhìn thấy trong đoạn mã sau. Chúng ta thấy rằng
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
95 trả về
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
99 nếu chúng ta so sánh một đối tượng với lớp mà nó thuộc về hoặc với siêu lớp. Trong khi toán tử đẳng thức chỉ trả về
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
99, nếu chúng ta so sánh một đối tượng với lớp của chính nó

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)

ĐẦU RA

import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
9

Điều này thậm chí đúng với tổ tiên tùy ý của lớp trong dòng thừa kế

class DerivedClassName(BaseClassName):
    pass
0

ĐẦU RA

class DerivedClassName(BaseClassName):
    pass
1

Bây giờ thì rõ ràng, tại sao PEP 8, Hướng dẫn phong cách chính thức cho mã Python, nói. "So sánh loại đối tượng phải luôn sử dụng isinstance() thay vì so sánh trực tiếp các loại. "

ghi đè

Hãy để chúng tôi quay lại lớp học

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1 mới của chúng tôi. Bây giờ hãy tưởng tượng rằng một phiên bản của
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1 sẽ nói xin chào theo một cách khác. Trong trường hợp này, chúng ta phải định nghĩa lại phương thức
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
7 bên trong lớp con
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1

class DerivedClassName(BaseClassName):
    pass
6

ĐẦU RA

class DerivedClassName(BaseClassName):
    pass
7

Những gì chúng ta đã làm trong ví dụ trước được gọi là ghi đè. Một phương thức của lớp cha bị ghi đè bằng cách định nghĩa một phương thức có cùng tên trong lớp con

Nếu một phương thức bị ghi đè trong một lớp, thì phương thức ban đầu vẫn có thể được truy cập, nhưng chúng ta phải làm điều đó bằng cách gọi trực tiếp phương thức đó bằng tên lớp, i. e.

class DerivedClassName(BaseClassName):
    pass
05. Chúng tôi chứng minh điều này trong đoạn mã sau

class DerivedClassName(BaseClassName):
    pass
9

ĐẦU RA

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
0

Chúng ta đã thấy rằng một lớp kế thừa có thể kế thừa và ghi đè các phương thức từ lớp cha. Bên cạnh đó, một lớp con thường cần các phương thức bổ sung với các chức năng bổ sung, không tồn tại trong lớp cha. Ví dụ, một thể hiện của lớp

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
1 sẽ cần phương thức
class DerivedClassName(BaseClassName):
    pass
07 để bác sĩ có thể thực hiện công việc phù hợp. Chúng ta cũng sẽ thêm một thuộc tính
class DerivedClassName(BaseClassName):
    pass
08 vào lớp
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
0, thuộc tính này có thể nhận giá trị trong khoảng từ
class DerivedClassName(BaseClassName):
    pass
10 đến
class DerivedClassName(BaseClassName):
    pass
11. Các rô-bốt sẽ 'sống dậy' với giá trị ngẫu nhiên trong khoảng từ
class DerivedClassName(BaseClassName):
    pass
10 đến
class DerivedClassName(BaseClassName):
    pass
11. Nếu
class DerivedClassName(BaseClassName):
    pass
08 của một
x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
0 dưới 0. 8, nó sẽ cần một bác sĩ. Chúng ta viết một phương thức
class DerivedClassName(BaseClassName):
    pass
16 trả về
import types
import inspect

def strict(func):
    """Add some info for functions having strict signature.
    """
    arg_sig = inspect.getargspec(func)
    func.is_strict = True
    func.arg_signature = arg_sig
    return func


class StrictSignature(type):
    def __new__(cls, name, bases, attrs):
        func_types = (types.MethodType,) # include types.FunctionType?

        # Check each attribute in the class being created.
        for attr_name, attr_value in attrs.iteritems():
            if isinstance(attr_value, func_types):

                # Check every base for @strict functions.
                for base in bases:
                    base_attr = base.__dict__.get(attr_name)
                    base_attr_is_function = isinstance(base_attr, func_types)
                    base_attr_is_strict = hasattr(base_attr, "is_strict")

                    # Assert that inspected signatures match.
                    if base_attr_is_function and base_attr_is_strict:
                        assert (inspect.getargspec(attr_value) == 
                                base_attr.arg_signature)

        # If everything passed, create the class.
        return super(StrictSignature, cls).__new__(cls, name, bases, attrs)



# Make a base class to try out strictness
class Base:
    __metaclass__ = StrictSignature

    @strict
    def foo(self, a, b, c="blah"):
        return a + b + len(c)

    def bar(self, x, y, z):
        return x


#####
# Now try to make some classes inheriting from Base.
#####
class GoodChild(Base):

    # Was declared strict, better match the signature.
    def foo(self, a, b, c="blah"):
        return c

    # Was never declared as strict, so no rules!
    def bar(im_a_little, teapot):
        return teapot/2


# These below can't even be created. Uncomment and try to run the file
# and see. It's not just that you can't instantiate them, you can't
# even get the *class object* defined at class creation time.
#
#class WrongChild(Base):
#    def foo(self, a):
#        return super(self.__class__, self).foo(a, 5)
#
#class BadChild(Base):
#    def foo(self, a, b, c="halb"):
#        return super(self.__class__, self).foo(a, b, c)
99 nếu giá trị thấp hơn
class DerivedClassName(BaseClassName):
    pass
18 và ngược lại là
class DerivedClassName(BaseClassName):
    pass
19. Việc 'chữa bệnh' trong phương pháp
class DerivedClassName(BaseClassName):
    pass
07 được thực hiện bằng cách đặt
class DerivedClassName(BaseClassName):
    pass
08 thành một giá trị ngẫu nhiên giữa
class DerivedClassName(BaseClassName):
    pass
08 cũ và 1. Giá trị này được tính toán bởi hàm thống nhất của mô-đun ngẫu nhiên

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
1

ĐẦU RA

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
2

Khi ghi đè một phương thức, đôi khi chúng ta muốn sử dụng lại phương thức của lớp cha và một số nội dung mới. Để chứng minh điều này, chúng ta sẽ viết một phiên bản mới của PhysicianRobot.

x = Robot("Marvin")
y = PhysicianRobot("James")
print(isinstance(x, Robot), isinstance(y, Robot))
print(isinstance(x, PhysicianRobot))
print(isinstance(y, PhysicianRobot))
print(type(y) == Robot, type(y) == PhysicianRobot)
7 sẽ trả về văn bản từ phiên bản lớp Người máy cộng với văn bản " và tôi là bác sĩ. "

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
3

ĐẦU RA

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
4

Chúng tôi không muốn viết mã dư thừa và do đó chúng tôi gọi là

class DerivedClassName(BaseClassName):
    pass
64. Chúng ta cũng có thể sử dụng hàm
class DerivedClassName(BaseClassName):
    pass
65

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
5

ĐẦU RA

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
4

class DerivedClassName(BaseClassName):
    pass
65 không thực sự cần thiết trong trường hợp này. Người ta có thể lập luận rằng nó làm cho mã dễ bảo trì hơn, bởi vì chúng ta có thể thay đổi tên của lớp cha, nhưng dù sao thì điều này hiếm khi được thực hiện trong các lớp hiện có. Lợi ích thực sự của
class DerivedClassName(BaseClassName):
    pass
65 thể hiện khi chúng ta sử dụng nó với đa kế thừa

Đào tạo Python trực tiếp

Phương thức kế thừa trong Python là gì?

Thưởng thức trang này?

Nhìn thấy. Tổng quan về các khóa học Python trực tiếp

đăng ký tại đây

Phân biệt giữa ghi đè, nạp chồng và ghi đè

ghi đè

Nếu chúng ta ghi đè lên một chức năng, chức năng ban đầu sẽ biến mất. Chức năng sẽ được định nghĩa lại. Quá trình này không liên quan gì đến hướng đối tượng hoặc kế thừa

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
7

ĐẦU RA

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
8

quá tải

Chương phụ này sẽ chỉ thú vị đối với các lập trình viên C++ và Java, những người muốn biết cách nạp chồng có thể được thực hiện trong Python. Ai chưa biết về quá tải thì đừng bỏ qua

Trong bối cảnh lập trình hướng đối tượng, bạn cũng có thể đã nghe nói về "quá tải". Mặc dù "quá tải" không được kết nối trực tiếp với OOP. Quá tải là khả năng định nghĩa một hàm có cùng tên nhiều lần. Các định nghĩa khác nhau liên quan đến số lượng tham số và loại tham số. Đó là khả năng của một chức năng thực hiện các tác vụ khác nhau, tùy thuộc vào số lượng tham số hoặc loại tham số. Chúng ta không thể quá tải các hàm như thế này trong Python, nhưng cũng không cần thiết

Tuy nhiên, khóa học này không phải về C++ và cho đến nay chúng tôi đã tránh sử dụng bất kỳ mã C++ nào. Bây giờ chúng tôi muốn tạo một ngoại lệ để bạn có thể thấy quá tải hoạt động như thế nào trong C++

class Robot:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
    pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()
9

Chúng tôi đã xác định chức năng kế thừa hai lần. Một lần cho int và lần khác với float làm Tham số. Trong Python, hàm có thể được định nghĩa như thế này, chắc chắn bạn sẽ biết

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
0

Vì x chỉ là một tham chiếu đến một đối tượng, hàm kế nhiệm Python có thể được gọi với mọi đối tượng, mặc dù nó sẽ tạo ra các ngoại lệ với nhiều loại. Nhưng nó sẽ hoạt động với các giá trị int và float

Có một hàm với một số lượng tham số khác nhau là một cách nạp chồng hàm khác. Chương trình C++ sau đây cho thấy một ví dụ như vậy. Hàm f có thể được gọi với một hoặc hai đối số nguyên

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
1

Điều này không hoạt động trong Python, như chúng ta có thể thấy trong ví dụ sau. Định nghĩa thứ hai của f với hai tham số xác định lại hoặc ghi đè định nghĩa đầu tiên bằng một đối số. Ghi đè có nghĩa là định nghĩa đầu tiên không còn nữa

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
2

ĐẦU RA

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
3

Nếu bạn gọi f chỉ với một tham số, bạn sẽ đưa ra một ngoại lệ

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
4

Tuy nhiên, có thể mô phỏng hành vi nạp chồng của C++ bằng Python trong trường hợp này với tham số mặc định

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
5

ĐẦU RA

<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
6

Toán tử * có thể được sử dụng như một cách tiếp cận tổng quát hơn cho một họ các hàm có 1, 2, 3 hoặc thậm chí nhiều tham số hơn

Phương pháp kế thừa là gì?

Kế thừa là thủ tục trong đó một lớp kế thừa các thuộc tính và phương thức của lớp khác . Lớp có các thuộc tính và phương thức được kế thừa được gọi là lớp Cha. Và lớp kế thừa các thuộc tính từ lớp cha là lớp Con.

Kế thừa trong Python với ví dụ là gì?

Mối quan hệ kế thừa xác định các lớp kế thừa từ các lớp khác dưới dạng lớp dẫn xuất, lớp con hoặc lớp con . Lớp cơ sở vẫn là nguồn mà lớp con kế thừa. Ví dụ: bạn có lớp Cơ sở là “Động vật” và “Sư tử” là lớp Dẫn xuất. Quyền thừa kế sẽ là Sư tử là một con vật.

3 loại thừa kế là gì?

Khám phá 5 loại kế thừa trong C++ với các ví dụ .
Thừa kế đơn
Đa thừa kế
Kế thừa đa cấp
Kế thừa phân cấp
Kế thừa lai

Thừa kế là gì và các loại của nó?

Kế thừa là cơ chế lấy các tính năng và hành vi của một lớp bởi một lớp khác . Lớp có các thành viên được kế thừa gọi là lớp cơ sở, lớp kế thừa các thành viên đó gọi là lớp dẫn xuất. Kế thừa thực hiện mối quan hệ IS-A.