1

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"]

schanti schul
  • 681
  • 3
  • 14
  • use the `__str__` ? https://docs.python.org/3/reference/datamodel.html#object.__str__ - or do you need it for other things then output? if so, edit your questions pls. – Patrick Artner Dec 17 '17 at 13:25

2 Answers2

3

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']
Zionsof
  • 1,196
  • 11
  • 23
2
def asList(self):
    return [a,b,....] # will create a new list on each call

Unless you also create an __init__(...) or factory methods or something alike 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

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69