Skip to content Skip to sidebar Skip to footer

Write Class Such That Calling Instance Returns All Instance Variables

I have answered my own question - see answer below I'm writing a class, and I want this behavior: a = f(10,20) some_funct(a.row) # some_function is given 10 some_funct(a.col) # som

Solution 1:

You can do like this

classf(object):
    """Simple 2d object"""
    row: int
    col: intdef__init__(self, row, col):
        self.row = row
        self.col = col

    def__str__(self):
        returnf"row = {row}, col = {col}"

and print like this

a = f(10,20)

print(a)     # row = 10, col = 20

Solution 2:

This might help

classf(object):
    """Simple 2d object"""
    row: int
    col: intdef__init__(self, row, col):
        self.row = row
        self.col = col

    defsome_funct(self):
        return (self.row, self.col)

You can access like

a = f(10,20)
a.some_funct() # (10, 20)# or
row, col = a.some_funct()

Solution 3:

From python 3.7 dataclasses have been introduced and their goal is to create classes that mainly contains data. Dataclasses comes with some helper function that extract the class attributes dict/tuples. e.g.

from dataclasses import dataclass,asdict,astuple
@dataclassclassf:
 x: int
 y: int

f_instance = f(10,20)
asdict(f_instance) # --> {'x': 10, 'y': 20}
astuple(f_instance) # -> (10,20)

EDIT I : Another technique would be to use namedtuple e.g.:

from collections import namedtuple
f = namedtuple('p',['row','col'])
a =f(10,20)
a.row #-> 10
a.col #-> 20

Solution 4:

classf(tuple):
    """Simple 2d object"""def__new__(cls, x, y):
        returntuple.__new__(f, (x, y))

    def__init__(self, x, y):
        self.col = x
        self.row = y

foo = f(1,2)
print(foo.col)
>>>1print(foo.row)
>>>2print(foo)
>>>(1, 2)

Importantly: If you want it to behave like a tuple then make it a subclass of tuple.

Much stuffing around but stumbled upon an external site which gave me clues about the keywords to search on here. The SO question is here but I have modified that answer slightly. I'm still a little confused because the other site says to use new in the init as well but does not give a clear example.

Post a Comment for "Write Class Such That Calling Instance Returns All Instance Variables"