apply python class methods on list of instances











up vote
0
down vote

favorite












I recently moved from Matlab to Python and want to transfer some Matlab code to Python. However an obstacle popped up.



In Matlab you can define a class with its methods and create nd-arrays of instances. The nice thing is that you can apply the class methods to the array of instances as long as the method is written so it can deal with the arrays. Now in Python I found that this is not possible: when applying a class method to a list of instances it will not find the class method. Below an example of how I would write the code:



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
times5(classlist)


This will give an error on the times5(classlist) line. Now this is a simple example explaining what I want to do (the final class will have multiple numpy arrays as variables).



What is the best way to get this kind of functionality in Python? The reason I want to do this is because it allows batch operations and they make the class a lot more powerful. The only solution I can think of is to define a second class that has a list of instances of the first class as variables. The batch processing would need to be implemented in the second class then.



thanks!










share|improve this question









New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
    – PM 2Ring
    Nov 18 at 9:08






  • 1




    You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
    – PM 2Ring
    Nov 18 at 9:13












  • You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
    – David Scott IV
    Nov 18 at 9:16















up vote
0
down vote

favorite












I recently moved from Matlab to Python and want to transfer some Matlab code to Python. However an obstacle popped up.



In Matlab you can define a class with its methods and create nd-arrays of instances. The nice thing is that you can apply the class methods to the array of instances as long as the method is written so it can deal with the arrays. Now in Python I found that this is not possible: when applying a class method to a list of instances it will not find the class method. Below an example of how I would write the code:



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
times5(classlist)


This will give an error on the times5(classlist) line. Now this is a simple example explaining what I want to do (the final class will have multiple numpy arrays as variables).



What is the best way to get this kind of functionality in Python? The reason I want to do this is because it allows batch operations and they make the class a lot more powerful. The only solution I can think of is to define a second class that has a list of instances of the first class as variables. The batch processing would need to be implemented in the second class then.



thanks!










share|improve this question









New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
    – PM 2Ring
    Nov 18 at 9:08






  • 1




    You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
    – PM 2Ring
    Nov 18 at 9:13












  • You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
    – David Scott IV
    Nov 18 at 9:16













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I recently moved from Matlab to Python and want to transfer some Matlab code to Python. However an obstacle popped up.



In Matlab you can define a class with its methods and create nd-arrays of instances. The nice thing is that you can apply the class methods to the array of instances as long as the method is written so it can deal with the arrays. Now in Python I found that this is not possible: when applying a class method to a list of instances it will not find the class method. Below an example of how I would write the code:



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
times5(classlist)


This will give an error on the times5(classlist) line. Now this is a simple example explaining what I want to do (the final class will have multiple numpy arrays as variables).



What is the best way to get this kind of functionality in Python? The reason I want to do this is because it allows batch operations and they make the class a lot more powerful. The only solution I can think of is to define a second class that has a list of instances of the first class as variables. The batch processing would need to be implemented in the second class then.



thanks!










share|improve this question









New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I recently moved from Matlab to Python and want to transfer some Matlab code to Python. However an obstacle popped up.



In Matlab you can define a class with its methods and create nd-arrays of instances. The nice thing is that you can apply the class methods to the array of instances as long as the method is written so it can deal with the arrays. Now in Python I found that this is not possible: when applying a class method to a list of instances it will not find the class method. Below an example of how I would write the code:



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
times5(classlist)


This will give an error on the times5(classlist) line. Now this is a simple example explaining what I want to do (the final class will have multiple numpy arrays as variables).



What is the best way to get this kind of functionality in Python? The reason I want to do this is because it allows batch operations and they make the class a lot more powerful. The only solution I can think of is to define a second class that has a list of instances of the first class as variables. The batch processing would need to be implemented in the second class then.



thanks!







python list matlab class






share|improve this question









New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 18 at 16:49





















New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 18 at 8:53









StefanVR

22




22




New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
    – PM 2Ring
    Nov 18 at 9:08






  • 1




    You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
    – PM 2Ring
    Nov 18 at 9:13












  • You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
    – David Scott IV
    Nov 18 at 9:16


















  • You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
    – PM 2Ring
    Nov 18 at 9:08






  • 1




    You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
    – PM 2Ring
    Nov 18 at 9:13












  • You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
    – David Scott IV
    Nov 18 at 9:16
















You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
– PM 2Ring
Nov 18 at 9:08




You should consider learning Numpy, once you're comfortable with core Python. Numpy can efficiently do arithmetic on arrays of numbers, but it does not speed up the execution of methods on general Python objects.
– PM 2Ring
Nov 18 at 9:08




1




1




You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
– PM 2Ring
Nov 18 at 9:13






You can make that list using a list comprehension: [u.times5() for u in classlist]. And you can populate the input list like classlist = [testclass(u) for u in (1, 10, 100)]. And those can be combined if you don't actually need to keep classlist.
– PM 2Ring
Nov 18 at 9:13














You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
– David Scott IV
Nov 18 at 9:16




You have to use the method on the class itself... so it's defined as a method of testclass(), so you would have to have to do: instance = testclass(1)
– David Scott IV
Nov 18 at 9:16












1 Answer
1






active

oldest

votes

















up vote
0
down vote













UPDATE:



In your comment , I notice this sentence,




For example a function that takes the data of the first class in the list and substracts the data of all following classe.




This can be solved by reduce function.



class testclass():
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)


ORIGIN ANSWER:



In fact, what you need is List Comprehensions.



Please let me show you the code



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)





share|improve this answer























  • Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
    – StefanVR
    Nov 18 at 16:53










  • @StefanVR I updated answer to solve your new problem.
    – Mark White
    Nov 19 at 3:17











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






StefanVR is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53359236%2fapply-python-class-methods-on-list-of-instances%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













UPDATE:



In your comment , I notice this sentence,




For example a function that takes the data of the first class in the list and substracts the data of all following classe.




This can be solved by reduce function.



class testclass():
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)


ORIGIN ANSWER:



In fact, what you need is List Comprehensions.



Please let me show you the code



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)





share|improve this answer























  • Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
    – StefanVR
    Nov 18 at 16:53










  • @StefanVR I updated answer to solve your new problem.
    – Mark White
    Nov 19 at 3:17















up vote
0
down vote













UPDATE:



In your comment , I notice this sentence,




For example a function that takes the data of the first class in the list and substracts the data of all following classe.




This can be solved by reduce function.



class testclass():
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)


ORIGIN ANSWER:



In fact, what you need is List Comprehensions.



Please let me show you the code



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)





share|improve this answer























  • Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
    – StefanVR
    Nov 18 at 16:53










  • @StefanVR I updated answer to solve your new problem.
    – Mark White
    Nov 19 at 3:17













up vote
0
down vote










up vote
0
down vote









UPDATE:



In your comment , I notice this sentence,




For example a function that takes the data of the first class in the list and substracts the data of all following classe.




This can be solved by reduce function.



class testclass():
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)


ORIGIN ANSWER:



In fact, what you need is List Comprehensions.



Please let me show you the code



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)





share|improve this answer














UPDATE:



In your comment , I notice this sentence,




For example a function that takes the data of the first class in the list and substracts the data of all following classe.




This can be solved by reduce function.



class testclass():
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)


ORIGIN ANSWER:



In fact, what you need is List Comprehensions.



Please let me show you the code



class testclass(): 
def __init__(self, data):
self.data = data
def times5(self):
return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 19 at 3:17

























answered Nov 18 at 9:37









Mark White

36729




36729












  • Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
    – StefanVR
    Nov 18 at 16:53










  • @StefanVR I updated answer to solve your new problem.
    – Mark White
    Nov 19 at 3:17


















  • Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
    – StefanVR
    Nov 18 at 16:53










  • @StefanVR I updated answer to solve your new problem.
    – Mark White
    Nov 19 at 3:17
















Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
– StefanVR
Nov 18 at 16:53




Thanks for this answer, however I want to keep the list comprehension part away from the class user. This batch functionality will not always be to execute a method on each instance in the list but will do more complex things. For example a function that takes the data of the first class in the list and substracts the data of all following classes.
– StefanVR
Nov 18 at 16:53












@StefanVR I updated answer to solve your new problem.
– Mark White
Nov 19 at 3:17




@StefanVR I updated answer to solve your new problem.
– Mark White
Nov 19 at 3:17










StefanVR is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StefanVR is a new contributor. Be nice, and check out our Code of Conduct.













StefanVR is a new contributor. Be nice, and check out our Code of Conduct.












StefanVR is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53359236%2fapply-python-class-methods-on-list-of-instances%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin