Hướng dẫn are methods inherited in python? - các phương thức được kế thừa trong python?

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

Điều tương tự cũng đúng ngay cả khi cha mẹ là 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

Đó là một bài tập thú vị trong các metaclass 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 phù hợp với lớp cơ sở. Đây là một nỗ lực.

Lưu ý: Tôi không chứng thực đây là một ý tưởng kỹ thuật tốt và tôi đã không dành thời gian để buộc các kết thúc lỏng lẻo nên có khả năng rất ít cảnh báo về mã bên dưới có thể làm cho nó hiệu quả hơn hoặc một cái gì đó.: I'm not endorsing this as a good engineering idea, and I did not spend time tying up loose ends so there are likely little caveats about the code below that could make it more efficient or something.

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ư với 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 tự do các chức năng của chú khỉ lên ngay cả một "lớp tốt" và các chức năng được gắn khỉ không phải thỏa mãn 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 bất kỳ thuộc tính loại phương thức nào được cập nhật trong __dict__ của lớp và tiếp tục thực hiện câu lệnh ____10 khi lớp được sửa đổi, bạn vẫn có thể sử dụ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)
1 để bỏ qua hành vi tùy chỉnh và đặt một thuộc tính nào .

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

Thừa kế trong Python

Kế thừa là một tính năng mạnh mẽ trong lập trình hướng đối tượng.

Nó đề cập đến việc xác định một lớp mới có ít hoặc không có sửa đổi cho một lớp hiện có. Lớp mới được gọi là lớp dẫn xuất (hoặc trẻ em) và lớp mà nó thừa hưởng được gọi là lớp cơ sở (hoặc cha mẹ).derived (or child) class and the one from which it inherits is called the base (or parent) class.


Cú pháp kế thừa Python

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class

Các lớp có nguồn gốc kế thừa các tính năng từ lớp cơ sở nơi các tính năng mới có thể được thêm vào nó. Điều này dẫn đến khả năng tái sử dụng mã.


Ví dụ về thừa kế trong Python

Để chứng minh việc sử dụng thừa kế, chúng ta hãy lấy một ví dụ.

Một đa giác là một hình đóng với 3 cạnh trở lên. Giả sử, chúng ta có một lớp gọi là

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)
2 được định nghĩa như sau.

class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])

Lớp này có các thuộc tính dữ liệu để lưu trữ số cạnh n và độ lớn của mỗi bên dưới dạng một danh sách được gọi là các bên.

Phương pháp

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)
3 có độ lớn của mỗi bên 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)
4 hiển thị các độ dài bên này.

Một tam giác là một đa giác với 3 cạnh. Vì vậy, chúng ta có thể tạo một lớp gọi là tam giác kế thừa từ đa giác. Điều này làm cho tất cả các thuộc tính của lớp đa giác có sẵn cho lớp tam giác.

Chúng ta không cần xác định lại chúng (khả năng tái sử dụng mã). Tam giác có thể được định nghĩa như sau.

class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self,3)

    def findArea(self):
        a, b, c = self.sides
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
        print('The area of the triangle is %0.2f' %area)

Tuy nhiên, lớp

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)
5 có phương pháp mới
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)
6 để tìm và in diện tích của tam giác. Đây là một mẫu chạy.

>>> t = Triangle()

>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> t.findArea()
The area of the triangle is 6.00

Chúng ta có thể thấy rằng mặc dù chúng ta không xác định các phương thức như

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)
3 hoặc
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)
4 cho lớp
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)
5 một cách riêng biệt, chúng ta đã có thể sử dụng chúng.

Nếu một thuộc tính không được tìm thấy trong bản thân lớp, tìm kiếm tiếp tục đến lớp cơ sở. Điều này lặp lại đệ quy, nếu lớp cơ sở có nguồn gốc từ các lớp khác.


Phương pháp ghi đè trong Python

Trong ví dụ trên, lưu ý rằng phương pháp

# 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!"
0 được xác định trong cả hai lớp, tam giác cũng như đa giác. Khi điều này xảy ra, phương thức trong lớp dẫn xuất sẽ ghi đè lên trong lớp cơ sở. Điều này có nghĩa là,
# 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!"
0 trong tam giác được ưu tiên so với
# 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!"
2 trong đa giác.

Nói chung khi ghi đè một phương thức cơ sở, chúng ta có xu hướng mở rộng định nghĩa thay vì chỉ đơn giản là thay thế nó. Điều tương tự đang được thực hiện bằng cách gọi phương thức trong lớp cơ sở từ lớp trong lớp có nguồn gốc (gọi

# 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!"
3 từ
# 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!"
0 trong
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)
5).

Một tùy chọn tốt hơn sẽ là sử dụng chức năng tích hợp

# 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!"
6. Vì vậy,
# 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!"
7 tương đương với
# 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!"
8 và được ưa thích. Để tìm hiểu thêm về hàm
# 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!"
6 trong Python, hãy truy cập hàm python Super ().

Hai chức năng tích hợp

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
0 và
class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
1 được sử dụng để kiểm tra các khoản thừa kế.

Hàm

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
0 trả về
class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
3 nếu đối tượng là một thể hiện của lớp hoặc các lớp khác có nguồn gốc từ nó. Mỗi và mọi lớp trong Python thừa hưởng từ lớp cơ sở
class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
4.

>>> isinstance(t,Triangle)
True

>>> isinstance(t,Polygon)
True

>>> isinstance(t,int)
False

>>> isinstance(t,object)
True

Tương tự,

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class
1 được sử dụng để kiểm tra kế thừa lớp.

>>> issubclass(Polygon,Triangle)
False

>>> issubclass(Triangle,Polygon)
True

>>> issubclass(bool,int)
True

Phương pháp lớp có được kế thừa không?

Vâng, họ có thể được thừa hưởng..

Những gì được thừa hưởng trong Python?

Kế thừa trong Python, nó đề cập đến việc xác định một lớp mới với rất ít hoặc không có sửa đổi cho một lớp hiện có.Lớp mới được gọi là lớp dẫn xuất (hoặc trẻ em) và lớp mà nó thừa hưởng được gọi là lớp cơ sở (hoặc cha mẹ).defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.

Các lớp con Python có kế thừa các phương pháp không?

Các lớp được gọi là các lớp con hoặc các lớp con kế thừa các phương thức và biến từ các lớp cha hoặc các lớp cơ sở.Chúng ta có thể nghĩ về một lớp cha mẹ được gọi là cha mẹ có biến lớp cho Last_name, Chiều cao và Eye_Color mà con cái con sẽ được thừa hưởng từ cha mẹ.. We can think of a parent class called Parent that has class variables for last_name , height , and eye_color that the child class Child will inherit from the Parent .

Phương pháp riêng tư có kế thừa python không?

Phương pháp riêng tư của Afaik không được thừa hưởng.stackoverflow.com/questions/8241462/private methods are not inherited. stackoverflow.com/questions/8241462/…