필터 지우기
필터 지우기

Is create a instance inside another class possible?

조회 수: 5 (최근 30일)
chen cui
chen cui 2021년 8월 10일
답변: Yongjian Feng 2021년 8월 11일
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