Python继承 – 接口/类

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

Python inheritance - Interfaces/classes

问题

  1. from langchain.schema import BaseMemory
  2. class ChatMemory(BaseMemory):
  3. def __init__(self, user_id: UUID, type: str):
  4. self.user_id = user_id
  5. self.type = type
  6. class AnotherMem(ChatMemory):
  7. def __init__(self, user_id: UUID, type: str):
  8. super().__init__(user_id, type)

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

  1. <details>
  2. <summary>英文:</summary>
  3. from langchain.schema import BaseMemory
  4. class ChatMemory(BaseMemory):
  5. def __init__(self, user_id: UUID, type: str):
  6. self.user_id = user_id
  7. self.type = type
  8. # implemented abstract methods
  9. class AnotherMem(ChatMemory):
  10. def __init__(self, user_id: UUID, type: str):
  11. super().__init__(user_id, type)
  12. 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?
  13. Note that [BaseMemory][1] is an interface.
  14. [1]: https://github.com/hwchase17/langchain/blob/db45970a66f39a32f2cdd83e7bde26a404efad7b/langchain/schema.py#L188
  15. </details>
  16. # 答案1
  17. **得分**: 0
  18. 看起来`BaseMemory`来自[langchain][1]被定义为[pydantic][2]模型,它对定义实例属性有严格的规定。不要使用构造函数方法,而是使用标准的 pydantic 语法,在子类上声明预期的实例属性。

import uuid
from langchain.schema import BaseMemory

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

  1. ...

class AnotherMem(ChatMemory):
pass

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

d952d62e-79e0-4cf4-a786-d23d880f96a2

  1. [1]: https://pypi.org/project/langchain/
  2. [2]: https://pypi.org/project/pydantic/
  3. <details>
  4. <summary>英文:</summary>
  5. 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

  1. ...

class AnotherMem(ChatMemory):
pass

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

d952d62e-79e0-4cf4-a786-d23d880f96a2

  1. [1]: https://pypi.org/project/langchain/
  2. [2]: https://pypi.org/project/pydantic/
  3. </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:

确定