Python继承 – 接口/类

huangapple go评论68阅读模式
英文:

Python inheritance - Interfaces/classes

问题

from langchain.schema import BaseMemory

class ChatMemory(BaseMemory):
    def __init__(self, user_id: UUID, type: str):
        self.user_id = user_id
        self.type = type

class AnotherMem(ChatMemory):
    def __init__(self, user_id: UUID, type: str):
        super().__init__(user_id, type)

出现错误信息:“ValueError: "AnotherMem"对象没有字段"user_id"”。我做错了什么?
请注意,BaseMemory是一个接口。


<details>
<summary>英文:</summary>

    from langchain.schema import BaseMemory

    class ChatMemory(BaseMemory):
       def __init__(self, user_id: UUID, type: str):
        self.user_id = user_id
        self.type = type

       # implemented abstract methods

    class AnotherMem(ChatMemory):
        def __init__(self, user_id: UUID, type: str):
            super().__init__(user_id, type)

This seems simple enough - but I get an error: `ValueError: &quot;AnotherMem&quot; object has no field &quot;user_id&quot;`. What am I doing wrong?

Note that [BaseMemory][1] is an interface. 


  [1]: https://github.com/hwchase17/langchain/blob/db45970a66f39a32f2cdd83e7bde26a404efad7b/langchain/schema.py#L188

</details>


# 答案1
**得分**: 0

看起来`BaseMemory`来自[langchain][1]被定义为[pydantic][2]模型,它对定义实例属性有严格的规定。不要使用构造函数方法,而是使用标准的 pydantic 语法,在子类上声明预期的实例属性。

import uuid
from langchain.schema import BaseMemory

class ChatMemory(BaseMemory):
user_id: uuid.UUID
type: str

...

class AnotherMem(ChatMemory):
pass

print(AnotherMem(user_id=uuid.uuid4(), type="foo").user_id)

d952d62e-79e0-4cf4-a786-d23d880f96a2


  [1]: https://pypi.org/project/langchain/
  [2]: https://pypi.org/project/pydantic/

<details>
<summary>英文:</summary>

It looks like `BaseMemory` from [langchain][1] is defined as a [pydantic][2] model, which has strict rules for defining instance attributes. Instead of using a constructor method, use the standard pydantic syntax of declaring expected instance attributes on the child class.

import uuid
from langchain.schema import BaseMemory

class ChatMemory(BaseMemory):
user_id: uuid.UUID
type: str

...

class AnotherMem(ChatMemory):
pass

print(AnotherMem(user_id=uuid.uuid4(), type="foo").user_id)

d952d62e-79e0-4cf4-a786-d23d880f96a2


  [1]: https://pypi.org/project/langchain/
  [2]: https://pypi.org/project/pydantic/

</details>



huangapple
  • 本文由 发表于 2023年6月2日 11:50:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定