I have a simple python class that consists of some attributes and some methods.What i need is to make a list out of the class attributes ( only ! )
Class A():
def __init__(self, a=50, b="ship"):
a = a
b = b
def method1():
.....
I want to have a list :
[50, "ship"]
def asList(self):
return [a,b,....] # will create a new list on each call
Unless you also create an __init__(...)
or factory methods or smth aloke for your class that decomposes this list you wont be able to create a new object back from the list. See how-to-overload-init-method-based-on-argument-type
Another solution, possibly more generic, is:
def asList(self):
[value for value in self.__dict__.values()]
Full example with correct syntax:
class A:
def __init__(self, a=50, b="ship"):
self.a = a
self.b = b
def as_list(self):
return [value for value in self.__dict__.values()]
a = A()
print a.as_list()
output:
[50, 'ship']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.