如何在Java或PDE中打印实例的内容?
class bouncingBall():
def __init__(self, bounce, window, position):
self.bounce = bounce
self.window = window
self.position = position
ball = bouncingBall(0.35, 1.5, 0.75)
print(ball) # <__main__.bouncingBall object at 0x0000025980427D60>
print(ball.__dict__) # {'bounce': 0.35, 'window': 1.5, 'position': 0.75}
检查实例的内部?
在Python中,我们可以使用对象.__ dict __
如何在 .java
或 .pde
中
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如Saksham(+1)指向您的那样,一个选项是覆盖
toString()
:这是手动的,但没有反射的开销。您也可以使用 java.lang.reflect。*; 您可以将其用于UTITTY功能在超级类中,您所有的子类都将继承此特征(每个子类都无需手动覆盖
toString()
),但是您将花费一些CPU时间来反映。这是一个非常粗略的示例,展示了这两个:
更新
在Python中,很高兴您获得
dict
回来,您可以进一步使用。在Java中,从理论上讲,您可以返回
hashmap
(或类似的地图结构),但是您只能关联相同类型的键。在这种情况下,由于所有属性都是浮动的,但是您可能会有属性是布尔人,浮点,ints等的情况。
可以使用 jsonobject https://processing.org/reference/savejsonobject_.html” serialize/将数据保存到磁盘中
通过
savestrings()
)同样,您可以使用反射将加载的JSON数据映射到实例属性。
As Saksham(+1) points you, one option is to override
toString()
: this is manual, but it doesn't have the overhead of reflection.You can also use java.lang.reflect.*; which you could use for a utilty function in a superclass, then all your subclasses will inherit this trait (no need to manually override
toString()
for each subclass), however you will spend a bit of CPU time reflecting.Here's a very rough example demonstrating both:
Update
In Python, it's nice you get a
dict
back which you can use further.In Java, in theory you could return a
HashMap
(or similar Map structure), however you can only associate keys of the same type.In this case, since all properties are float that would work, however you might have situations where the properties would be booleans, floats, ints, etc.
A workaround for this could be using JSONObject: a nice side effect of this option is you could easily serialize/save the data to disk via
saveJSONObject()
:(Notice the manual option of formatting toString() so the data is valid JSON also works (an can be saved to disk via
saveStrings()
)Similarly you could use reflection to map loaded JSON data to instance properties should you need to.
您可以在球类中覆盖
toString
并打印实例数据你自己。
或者,您可以使用反射
所有字段数据并打印
You can override
toString
in your Ball class and print the instance datayourself.
Or you can use reflection Get the class instance variables and print their values using reflection to get
all the fields data and print it