Using attributes from one class into another - python

In python, I want to create a coordinate system with two classes in separate scripts; lines and points where point class is just x,y and z coordinates and line class then have two of these points as attributes. My problem is that I don't understand how to write line class so it understands it is points it is getting and how to retrieve for example x in a point in line class. Point class looks like this:
class point:
def __init__(self, x, y, z=0):
self.x = float(x)
self.y = float(y)
self.z = float(z)
I am not certain how to write the line class but it looks something like this:
import point
import math
class line(point):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def length(self):
return math.sqrt((self.p2.x-self.p1.x)+(self.p2.y-self.p1.y))
Where I should then be able to create objects either like
line = line((1,2), (3,4,5))
or like
p1 = point.point(1,2)
p2 = point.point(3,4,5)
line = line(p1,p2)
I also want to be able to create functions like the one in line class and to retrieve coordinates in something like
line.p2.x
or
line.p2[0]
giving me (in this case) the output of 3. I also don't want point to be a subclass since there can be points not belonging to a line. Perhaps there is already a good answer to how to implement line class in such a way but I haven't found or understood it. Most examples is either about subclasses or separate classes which doesn't send or share some attributes. Thanks in advance for the help.

First: classes should be title capitalized, so that the proper names would be Line and Point - that make them easy to separate from plain variables.
As you've mentioned, inheriting from Point isn't the way to go - since a Line isn't a point. But you're almost there with your example:
from point import Point
import math
class Line:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def length(self):
return math.sqrt((self.p2.x-self.p1.x)+(self.p2.y-self.p1.y))
Line(Point(x1, y1), Point(x2, y2)) # should work
You can also use Python 3.6+'s typing support to say that you expect Point objects:
class Line:
def __init__(self, p1: Point, p2: Point):
self.p1 = p1
self.p2 = p2
....

A tuple is not a point, and line.__init__ will not automatically know to make the conversion. While you could add logic to line.__init__ to detect the type of argument, I would recommend separate functions for creating lines from tuples and points. Which you choose as the "canonical" argument is up to you. Here's an example using point.
class Line:
def __init__(self, p1: point, p2: point):
self.p1 = p1
self.p2 = p2
#classmethod
def from_tuples(cls, p1, p2):
return cls(point(*p1), point(*p2))
line1 = Line.from_tuples((1,2), (3,4,5))
p1 = point(1,2)
p2 = point(3,4,5)
line = Line(p1,p2)
Based on how you want to use point, I would recommend a namedtuple, and again leave the responsibility to pass the correct type of argument to the caller.
Point = namedtuple('Point', 'x y z')
p1 = Point(1.0, 2.0) # p.x == p[0] == 1

Related

How to control type casting for my classes

How can I control type casting for my classes? I know there is __int__() or __str__(), but what about other types? E.g. I have two classes Point and Vector. Is it possible to do something like:
point = Point(1, 2, 3)
# the following should not call Vector._init_(), but use a cast defined in Point
# (something like Point.__Vector__())
vector = Vector(point)
Is this possible? If so, how can I achieve such behavior? If not, for what standard types could I define a cast function to allow e.g. tuple(point) or list(point) - couldn't find this in the python documentation.
You could do it via the use of classmethods.
For example,
from point import Point # where the Point object is defined
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
#classmethod
def from_point(cls, point):
if not isinstance(point, Point): # some validation first
raise TypeError("The given object is not of type 'Point'")
return cls(point.x, point.y, point.z)
# other methods
Thus, then if you have a p = Point(1, 0, 0) then you can do v = Vector.from_point(p) and you'll have what you were looking for.
There are quite some improvements that could be applied but depend on the details of Point.

From Point class to Linestring class

I have created a Point class that takes x,y coords as arguments. Also I wanted to create a Linestring class that takes as many arguments as the user wants and store them as points. So far :
class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
def move(self,movex,movey):
self.x += movex
self.y += movey
class LineString(object):
def __init__(self, *args):
self.points = [Point(*p) for p in args]
So now I have stored in self.points a list of points.
The questions is how can I use the move function of points, in the class linestring.
I tried something like that but it does not work
def moveline(self,movex,movey):
self.points.move(movex,movey)
To spell out exactly what #MichaelButscher stated in the comments, the issue with your moveline function is that self.points is a list of Point objects rather than a Point object itself. Therefore, we need to iterate through this list and call the move function for each of these Point objects. This can be accomplished with a for loop. Your updated moveline function could look like this:
def moveline(self,movex,movey):
for point in self.points:
point.move(movex,movey)

Python __sub__ usage with class instances

class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __sub__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1 = Point(3, 4)
p2 = Point(1, 2)
result = p1-p2
print(result.x, result.y) # prints (4,6)
Can anyone explain how the above code works. Can't get my head around it.
I understand that __sub__ is an operator overloader in python and intercepts the p1-p2 call. But how does it work with two separate instances of class ?
__sub__ is supposed to be the magic method equivalent of - arithmetic operator, so not sure why you're adding them...
That aside, when you do p1 - p2, it is the same as p1.__sub__(p2). The __sub__ function is invoked on p1, the calculation made and the new Point object returned.
Now you edited the question, the answer is simple:
p1 = Point(3, 4)
p2 = Point(1, 2)
result = p1-p2
You have two points as arguments self, other, so, self, obviously in your example would be p1, and other is p2, after doing all the calculation, you return a new Point, so, p1 and p2 are not modified.
Important advice
The most rare thing, is that you call it __sub__, but indeed, you are actually adding! I mean, please... either change the method definition and replace + by -, or change __sub__... just a piece of advice.

Python method calls in constructor and variable naming conventions inside a class

I try to process some data in Python and I defined a class for a sub-type of data. You can find a very simplified version of the class definition below.
class MyDataClass(object):
def __init__(self, input1, input2, input3):
"""
input1 and input2 are a 1D-array
input3 is a 2D-array
"""
self._x_value = None # int
self._y_value = None # int
self.data_array_1 = None # 2D array
self.data_array_2 = None # 1D array
self.set_data(input1, input2, input3)
def set_data(self, input1, input2, input3):
self._x_value, self._y_value = self.get_x_and_y_value(input1, input2)
self.data_array_1 = self.get_data_array_1(input1)
self.data_array_2 = self.get_data_array_2(input3)
#staticmethod
def get_x_and_y_value(input1, input2):
# do some stuff
return x_value, y_value
def get_data_array_1(self, input1):
# do some stuff
return input1[self._x_value:self._y_value + 1]
def get_data_array_2(self, input3):
q = self.data_array_1 - input3[self._x_value:self._y_value + 1, :]
return np.linalg.norm(q, axis=1)
I'm trying to follow the 'Zen of Python' and thereby to write beautiful code. I'm quite sceptic, whether the class definition above is a good pratice or not. While I was thinking about alternatives I came up with the following questions, to which I would like to kindly get your opinions and suggestions.
Does it make sense to define ''get'' and ''set'' methods?
IMHO, as the resulting data will be used several times (in several plots and computation routines), it is more convenient to create and store them once. Hence, I calculate the data arrays once in the constructor.
I do not deal with huge amount of data and therefore processing takes not more than a second, however I cannot estimate its potential implications on RAM if someone would use the same procedure for huge data.
Should I put the function get_x_and_y_value() out of the class scope and convert static method to a function?
As the method is only called inside the class definition, it is better to use it as a static method. If I should define it as a function, should I put all the lines relevant to this class inside a script and create a module of it?
The argument naming of the function get_x_and_y_value() are the same as __init__ method. Should I change it?
It would ease refactoring but could confuse others who read it.
In Python, you do not need getter and setter functions. Use properties instead. This is why you can access attributes directly in Python, unlike other languages like Java where you absolutely need to use getters and setters and to protect your attributes.
Consider the following example of a Circle class. Because we can use the #property decorator, we don't need getter and setter functions like other languages do. This is the Pythonic answer.
This should address all of your questions.
class Circle(object):
def __init__(self, radius):
self.radius = radius
self.x = 0
self.y = 0
#property
def diameter(self):
return self.radius * 2
#diameter.setter
def diameter(self, value):
self.radius = value / 2
#property
def xy(self):
return (self.x, self.y)
#xy.setter
def xy(self, xy_pair):
self.x, self.y = xy_pair
>>> c = Circle(radius=10)
>>> c.radius
10
>>> c.diameter
20
>>> c.diameter = 10
>>> c.radius
5.0
>>> c.xy
(0, 0)
>>> c.xy = (10, 20)
>>> c.x
10
>>> c.y
20

Two objects in a method from a class?

I'm having a small issue with this code, I am currently learning about classes and trying to separate the two objects I have created to use both of them in a method from the class.
import math
class Segment:
def __init__(self, xcoord = 0, ycoord = 0):
self.x = xcoord
self.y = ycoord
def get(self):
return (self.x, self.y)
def setx(self, xcoord):
self.x = xcoord
def sety(self, ycoord):
self.y = ycoord
def length(self, xcoord, ycoord):
return math.sqrt(math.pow(xcoord-ycoord,2)+(xcoord-ycoord,2))
p1 = Segment(3,4)
p2 = Segment()
p2.setx(5)
p2.sety(5)
s = Segment(p1,p2)
print(Segment.get(p1))
print(Segment.get(p2))
print(s.length())
I know that I am missing parameters in my length() method, or perhaps I have not? I would like to understand how I am able to have the objects interact with on another after I have defined them.
For further clarity, I am trying to print the distance between the two objects using the parameters I have assigned to them.
Okay, let's forget the code for a second. Firstly, let's talk about naming things. Your Segment class is not a class of segments - it's a class of points. So let's start by renaming your class Point.
class Point:
def __init__(self, xcoord = 0, ycoord = 0):
self.x = xcoord
self.y = ycoord
Better already, no?
Now, imagine you're looking at someone else's code, trying to use that. Their Points have a length() method that you can call. What do you expect that to do? What could that... possibly do? A number of things, all because length is an awful descriptor for something that a Point is doing. It's certainly not a property of the Point - a point is 0-dimensional.
So let's rethink that function. There are two obvious ways to make this API - your Point class could have a distance_to(other_point) method, that would accept one argument - another Point. Optionally, you could have a module-level function segment_length(point1, point2) that would give you the length of the segment defined by the two Point objects.
So, the module-level function:
def segment_length(p1, p2):
return math.sqrt((p2.x-p1.x)**2 + (p2.y-p1.y)**2)
I'll leave the Point method to you, should you wish to attempt it. It looks very similar, just using self in lieu of one of the points.
Lets walk through this:
p1 is an instance of the Segment class with attributes x=3, y=4.
p2 is an instance of the Segment class with attributes x=0, y=0,
When you set p2 to (5, 5) you could do it with p2 = Segment(5, 5),
s will have attributes x=p1 (an instance of Segment, not a coordinate) and y=p2 (another instance of Segment).
Calculating the length.
Your length method should look like this:
def length(self, xcoord, ycoord):
return math.sqrt(math.pow(xcoord - self.x,2)+math.pow(ycoord - self.y,2))
This now uses the x and y coordinates of the class instance (in the example below, p1) and calculates the length between them, and the xcoord and ycoord parameters provided.
And you would call this with:
p2x, p2y = p2.get()
print(p1.length(p2x, p2y))
Firstly, you're missing a second math.pow() in your line:
return math.sqrt(math.pow(xcoord-ycoord,2)+(xcoord-ycoord,2))
Secondly with your call s = Segment(p1, p2) the x and y values of your Segment s are equal to the segments p1 and p2.
At the moment your values should read:
p1.get()
> (3, 4)
p2.get()
> (5, 5)
After the assignment of s you get:
s.get()
> ((3, 4), (5, 5))
This is problematic, because math.pow() has no idea what to do with a Segment object.

Categories