简体   繁体   English

Python:如何将Class function的参数类型指定为当前的ZA2F2ED4F8EBC2CBB4C21A9?

[英]Python: How do you specify the parameter type of a Class function to the current class?

I'm writing a set of custom classes with inheritance using Python.我正在使用 Python 编写一组带有 inheritance 的自定义类。 Here is the code, simplified:这是代码,简化:

class Parent(object):
    __slots__ = ['a','b']

    def __init__(self, a:int, b:int):
        self.a = a
        self.b = b
    
    def myfunc(self,s)->int:
        return self.a + s.a

class Child(Parent):
    __slots__ = ['c']

    def __init__(self, a:int, b:int, c:int):
        super().__init__(a,b)
        self.c = c

    def myfunc(self,s)->int:
        return self.a + s.a + s.c

def main():
    dad = Parent(1,2)
    son = Child(4,8,16)

    print(dad.myfunc(son))
    print(son.myfunc(son))
    print(son.myfunc(dad))

if __name__ == "__main__":
    main()

Upon running the function, I get this output (which I understand):在运行 function 后,我得到了这个 output(我理解):

5
24
Error: Parent has no attribute 'c'

The myfunc() definition in Child requires that both self AND s are instances of Child. Child 中的 myfunc() 定义要求 self 和 s 都是 Child 的实例。

My ideal functionality for this code is that I want to implement method overloading.我对这段代码的理想功能是我想实现方法重载。 When son.myfunc(dad) is called, I want it to check the type of dad.son.myfunc(dad)时,我希望它检查爸爸的类型。 If dad is also a Child , it should use Child 's definition of myfunc() .如果 dad 也是Child ,它应该使用Childmyfunc()定义。 Otherwise, if dad isn't a Child , son should fall back to using the definition of myfunc() in Parent .否则,如果 dad 不是Child ,则 son 应该回退到使用Parentmyfunc()的定义。 So, for the above code, I'd want:所以,对于上面的代码,我想要:

5
24
5

I would've thought that I could implement this functionality as follows, specifying the parameter types of myfunc() :我原以为我可以按如下方式实现此功能,指定myfunc()的参数类型:

class Parent(object):
    __slots__ = ['a','b']

    def __init__(self, a:int, b:int):
        self.a = a
        self.b = b
    
    def myfunc(self, s:Parent)->int:
        return self.a + s.a

class Child(Parent):
    __slots__ = ['c']

    def __init__(self, a:int, b:int, c:int):
        super().__init__(a,b)
        self.c = c

    def myfunc(self,s:Child)->int:
        return self.a + s.a + s.c

def main():
    dad = Parent(1,2)
    son = Child(4,8,16)

    print(dad.myfunc(son))
    print(son.myfunc(son))
    print(son.myfunc(dad))

if __name__ == "__main__":
    main()

However, this doesn't work.但是,这不起作用。 Python and my IDE tell me that "Parent is not defined" by the time I use it to specify the input type of Parent's myfunc() , and the same for Child . Python 和我的 IDE 告诉我,当我使用它来指定Parent's myfunc()的输入类型时, "Parent is not defined" ,对于Child也是如此。 I think I get what it's saying (' Parent ' won't mean anything until the compiler finishes reading Parent, so it can't be specified as the parameter type), but I don't know how to work around this.我想我明白它在说什么(在编译器完成读取 Parent 之前,' Parent '没有任何意义,因此不能将其指定为参数类型),但我不知道如何解决这个问题。

How can I implement my intended functionality?如何实现我的预期功能? Is there some keyword like 'this' or 'self' that can be used to refer to the current class's type for these specifications?是否有诸如'this''self'之类的关键字可用于引用这些规范的当前类的类型? Even if method overloading doesn't work in this way- is there a way for a single class ( Parent ) to specify itself as the parameter type of one of its functions?即使方法重载不能以这种方式工作 - 是否有办法让单个 class ( Parent )将自己指定为其函数之一的参数类型?

Edit: I'm aware that Python parameter types are annotations for readability and error-checking, and they don't actually cause errors/failures if called with a different type.编辑:我知道 Python 参数类型是用于可读性和错误检查的注释,如果使用不同的类型调用它们实际上不会导致错误/失败。 The second code segment was created to help communicate what I want to have occur.创建第二个代码段是为了帮助传达我想要发生的事情。 I'm aware I might have to add a check like isinstance() at the start of myfunc, but (a) I would like to avoid it if there is an alternative (b) if I did discover in the body of Child's myfunc() that I wanted to call the Parent's instead, I'm not certain of how I'd do that.我知道我可能必须在 myfunc 的开头添加一个类似 isinstance() 的检查,但是 (a) 如果有替代方法,我想避免它 (b) 如果我确实在 Child 的 myfunc( )我想打电话给父母,我不确定我会怎么做。

You have two separate issues:你有两个不同的问题:

  1. In order to type-hint a method that returns its own class ( forward reference ) you should use a string:为了对返回自己的 class (前向引用)的方法进行类型提示,您应该使用字符串:

     def myfunc(self, s: "Parent") -> int:
  2. You can use isinstance to check for type, ie您可以使用isinstance检查类型,即

    def myfunc(self, s: "Child") -> int: return (self.a + sa + sc) if isinstance(s, Child) else (self.a + sa)

As a side note the type of s in your Child.myfunc should probably be Parent .作为旁注,您Child.myfunc中的s类型可能应该是Parent

Update: Per your comment, the following should be possible:更新:根据您的评论,以下应该是可能的:

class Parent(object):
    # ...

    def _myfunc(self, s: "Parent") -> int:
        return self.a + s.a

    def myfunc(self, s: "Parent") -> int:
        return type(s)._myfunc(self, s)

class Child(Parent):
    # ...

    def _myfunc(self, s: "Parent") -> int:
        return self.a + s.a + s.c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM