Is create a instance inside another class possible?

5 次查看(过去 30 天)
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)

采纳的回答

Yongjian Feng
Yongjian Feng 2021-8-11
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 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by