필터 지우기
필터 지우기

How can I access the methods of a returned object?

조회 수: 5 (최근 30일)
Alex Henderson
Alex Henderson 2014년 11월 13일
답변: Philip Borghesani 2014년 11월 25일
I'd like to achieve the following, but don't know if it's possible.
I have a function that returns an object of a class. The returned object has a method. I'd like to access the method inline.
For example, say I have a class called myclass, with a method called classmethod. I also have a standalone function, myfunc, that takes a numeric argument and returns an instance of myclass. If I say...
obj = myfunc(123);
obj.classmethod();
...then everything is fine, although the workspace now has an additional variable (obj). Is it possible to say the following?
myfunc(123).classmethod();
I keep getting this error "??? Undefined variable "myfunc" or class "myfunc"."
Thanks, Alex

채택된 답변

Titus Edelhofer
Titus Edelhofer 2014년 11월 13일
Hi,
no, that's not possible. It's like with numeric arrays: you can't index into the result of a function directly. Suppose your myfunc returns a matrix.
myfunc(123)(1)
would not work either...
You could of course encapsulate this into some function that combines those two steps, but I doubt that makes sense.
By the way it looks weird to me that you create an object, want to call one method only and apparently have no use for the object afterwards? Nothing wrong with it per se, but seems not typical to me.
Titus
  댓글 수: 1
Alex Henderson
Alex Henderson 2014년 11월 25일
Hi Titus,
Ah that's a shame. Thanks for the information.
My use of the temporary object in this example is to generate class specific code for display (or some other procedure that doesn't return a variable). The temporary object is a storage class output from the previous function. I hoped to daisychain a collection of free functions that take different storage classes, and output other storage classes, where each storage class would know how to handle display etc.
Thanks for your help,
Alex

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Philip Borghesani
Philip Borghesani 2014년 11월 25일
Don't use dot to call the method:
classmethod(myfunc(123));
In MATLAB with standard objects there is no difference between obj.method(...) and method(obj,...) .
*By standard objects I mean one that does not have an overloaded subsref function.

카테고리

Help CenterFile Exchange에서 Methods에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by