python - Python为一个类封装数据
问题描述
我有两个继承自 A 的 Python 类 A 和 B。在运行时,我只有一个 A 类的实例,但有许多 B 类的实例。
class A:
def __init__(self, a):
self.a = a
def _init2 (self, AA)
self.a = AA.a
class B(A):
def __init__(self, AA, b):
super()._init2(AA)
self.b = b
AA = A(0)
BB = B(AA, 1)
这是写它的好方法吗?好像很丑...
解决方案
删除init2
并仅使用__init__
. 两者兼有是令人困惑和不自然的。
class A:
def __init__(self, obj):
# I believe that this is what you tried to achieve
if isinstance(obj, type(self)):
self.a = obj.a
else:
self.a = obj
class B(A):
def __init__(self, A, b):
super().__init__(A)
self.b = b
顺便说一句,这里调用的东西太多了A
。A
indef __init__(self, A, b):
很可能不是指您所A
期望的。
推荐阅读
- java - SWT Shell setRegion 在 macOS 的 Eclipse 闪屏中不起作用
- html - 为什么我的嵌套段落不尊重字体大小样式?
- html - 使用python提取文本时如何从URL中省略特定类
- c++ - OpenCV 像素访问点与 at() - 不同的值
- jira - 如何在 JIRA REST API 中传递多个用户名以获取批量用户?
- html - 在画布内插入文本
- php - 如何使用具有对象语法的数组循环对象?
- javascript - 如何为折线图指定限制颜色
- c# - 在不同阶段执行嵌套的异步函数
- amazon-web-services - 从应用程序的角度理解 AWS IoT