0

I have different python classes and I want to convert instances of these classes to ascii strings.Suppose that I have the following objects:

class A:
    name = "A"
    field = 2
    x = "a"

class B:
    name = "b"
    item = "c"

a = A()
b = B()

I want a function like serialize() which converts the objects as follows:

serialize(a) # results "A2a"
serialize(b) # results "bc"

I don't want to write a serialization function for every classe, I want to have a function capable of serializing all classes. One way is to use the dir() function to get a list of object attributes and then create a string out of them, but the dir() function does not return the attributes in the same order that they are defined. For example calling dir(a) would return ['__doc__', '__module__', 'filed', 'name', 'x'], and I cannot find out which attribute is defined first in the class.

Thanks.

3
  • 2
    You can overload the str_ or __repr magic methods however you want inside the class, or define your own class method to return the string representation however you like Commented Jan 20, 2020 at 14:43
  • 1
    would defining a serialize method in each of these classes be a valid option? Commented Jan 20, 2020 at 14:44
  • It would be best if I can do it in a general function that can serialize every class. I don't want to write a serialization function for every class! Commented Jan 21, 2020 at 9:39

2 Answers 2

2

You can override __repr__ function for print Object the desired way:

class A:
    name = "A"
    field = 2
    x = "a"

    def __repr__(self):
        return A.name + str(A.field) + A.x
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply but I don't want to write a serialize function for every class. I need a general serialization function that can serialize all classes.
@ayyoobimani Then you need a parent class for all classes and you need to define a serializer for the parent class.
@ARMAN and how does the serializer know about the order that the fields are added to the class?
@ayyoobimani actually it doesn't, you should consider naming attributes the same way and same order in child classes in order to define the serializer general.
1

You have to create methods in your classes: ON behalf to put the value in the class the best can be to pass argument of class A during the call%

class A:
    def __init__(self, name, field, x) :
    self.name = name
    self.field = field
    self.x = x

   def serialize(self) :
       return f"{self.name}{self.field}{self.x}"

#main:
a=A(name="a", field="field", x="x") 
result=a.serialize()
print(result) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.