首页 > 解决方案 > 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.

标签: pythonclassoop

解决方案


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

如果您想进一步阅读这个主题,这个过去的问题有一些很好的材料。


推荐阅读