Python Mixin - Unresolved Attribute Reference [PyCharm]

前端 未结 3 1712
借酒劲吻你
借酒劲吻你 2021-01-04 01:34

I am using a mixin to separate a range of functionality to a different class. This Mixin is only supposed to be mixable with the only child class:

class Mixi         


        
3条回答
  •  天涯浪人
    2021-01-04 01:56

    So just to compiling my thoughts from the comments for everyone else: The problem is keeping the two classes intrinsically connected while separating functionality. Here are my solutions:

    1) Make a module

    Have another file, say mixin.py, that has complex_operation as a function. Instead of accepting self as a parameter, have it take a string:

    # mixin.py
    
    def complex_operation (foo: str) -> str: return foo.capitalize()
    
    # main.py
    
    from ai import complex_operation
    class A: 
        def __init__(self): self.foo = "foo"
    print (complex_operation (A().foo))
    

    2) Make a class to accept another class as a parameter

    In Mixin's __init__ function, add a parameter to accept an A, and then use that in its methods:

    # mixin.py
    
    class Mixin: 
        def __init__(self, a: A): self.a = a
        def complex_operation(self): return self.a.foo.capitalize()
    
    # main.py
    
    from mixin import Mixin
    class A:
        def __init__(self): self.foo = "foo"
    
    print (Mixin (A()).complex_operation())
    

提交回复
热议问题