schanti schul
schanti schul

Reputation: 711

Class Attributes VALUES to a list

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

Upvotes: 1

Views: 1698

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

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

Upvotes: 2

Zionsof
Zionsof

Reputation: 1246

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

Upvotes: 3

Related Questions