英文:
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: "AnotherMem" object has no field "user_id"`. 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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论