Home > front end >  How to define method in python that takes the class type as a parameter?
How to define method in python that takes the class type as a parameter?

Time:10-13

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.

CodePudding user response:

Python is not a strongly typed language. This means that functions don't specifically take an instance of any particular type. You can always pass any object to any function!

Of course, if the object you are passing doesn't have the proper methods or attributes on it, well it's not going to work properly.

It's not exactly pythonic, but if you really want to ensure you only get objects of type Point, you could try something like

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

This past question has some good material if you want to read further around this topic.

CodePudding user response:

you can see this link maybe it will help in some way. here

  • Related