Is create a instance inside another class possible?

6 visualizaciones (últimos 30 días)
chen cui
chen cui el 10 de Ag. de 2021
Respondida: Yongjian Feng el 11 de Ag. de 2021
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)

Respuesta aceptada

Yongjian Feng
Yongjian Feng el 11 de Ag. de 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
>>

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by