Is create a instance inside another class possible?
9 views (last 30 days)
Show older comments
I wonder if a function in a class could create another class?
For example, surposing that there is a Point class, and a Vector class, i translate the properties Point.x, Point.y, Point.z in a Point instance with vector.x, vector.y, vector.z. The translate fuction creates a new Point instance instead of change the origin Point instance.
In python, i wrote like this,
class Point:
def __init__(self,x,y,z):
self.x,self.y,self.z = x, y, z
def translate(self,vector):
return Point(self.x+vector.x,self.y+vector.y,+self.z+vector.z)
or create another instance from the class
class Vector:
pass
class Point:
def __init__(self,x,y,z):
self.x,self.y,self.z = x, y, z
def vec(self):
return Vector(self.x,self.y,self.z)
0 Comments
Accepted Answer
Yongjian Feng
on 11 Aug 2021
Yes, it is doable:
classdef Apoint < handle
properties (Access=public)
x
y
end
methods
function ap = Apoint(x, y)
ap.x = x;
ap.y = y;
end
function np = translate(obj, x, y)
np = Apoint(obj.x + x, obj.y + y);
end
end
end
Then
>> p = Apoint(10, 10)
p =
Apoint with properties:
x: 10
y: 10
>> np = p.translate(5, 5)
np =
Apoint with properties:
x: 15
y: 15
>>
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!