python - How to define method in python that takes the class type as a parameter?
问题描述
I've been looking to see how to declare a method in a Python class that is the equivalent of how Java and C++ will take the class type as a parameter, as in a copy constructor method.
Java Class:
class Point {
protected float x;
protected float y;
public Point() {
this.x = 0.0f; this.y = 0.0f;
}
public Point( Point p ) {
this.x = p.x; this.y = p.y;
}
public boolean isEqual( Point p ) {
return this.x == p.x && this.y == p.y;
}
public void setValues( float x, float y ) {
this.x = x; this.y = y;
}
public void setValues( Point p ) {
this.x = p.x; this.y = p.y;
}
}
Here's the Python class I've go so far:
class Point:
def __init__(self):
self.x = 0.0;
self.y = 0.0;
def setValues( x, y ):
self.x = x
self.y = y
#def __init__( Point ): how to pass an instance of this class to copy the values?
#def isEquals( Point ): this would return True or False if the values are both equal.
#def setValues( Point ): how to pass an instance of Point?
I'm not familiar with Python so I'm not sure how to define a member function that would take it's class type as a parameter. What would the Python equivalent of a copy constructor, or the isEqual() method defined in the Java code?
Thanks.
解决方案
Python 不是强类型语言。这意味着函数不会专门采用任何特定类型的实例。您始终可以将任何对象传递给任何函数!
当然,如果您传递的对象没有正确的方法或属性,那么它就无法正常工作。
它不完全是pythonic,但如果你真的想确保你只得到类型的对象Point
,你可以尝试类似的东西
def setValues( self, point ):
if not isInstance( point, Point ):
# Assert? Return? Throw an exception? Up to you!
self.x = point.x
self.y = point.y
如果您想进一步阅读这个主题,这个过去的问题有一些很好的材料。
推荐阅读
- facebook - 找不到 Facebook 404 文件或目录
- filter - 如何在 PowerBI 动态过滤器中放置“V”标志?
- c - 为什么空数组的字符串长度与数组大小不同?
- python - 在 PyYAML 中使用表示器时控制折叠位置
- jenkins - SonarQube 扫描仪执行期间 Sonarqube 失败
- php - Woocommerce 订单详细信息未正确加载
- kubernetes-helm - Helm:在值 YAML 文件中使用变量
- elasticsearch - 来自容器化 WebApp 的日志不会通过 Serilog.Sinks.Elasticsearch 发送到 Elasticsearch
- python - 如何使用 google colab 在同一视频上创建第二个窗口
- laravel - Nginx 不显示页面 laravel