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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by