Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - what's your conventions to declare your attributes in a class?

In Python, I can declare attributes all over the class. For example :

class Foo:
def __init__(self):
    self.a = 0

def foo(self):
    self.b = 0

It's difficult to retrieve all attributes in my class when I have a big class with a lot of attributes.

Is it better to have the following code (a) or the next following code (b) :

a) Here, it's difficult to locate all attributes :

class Foo:
    def __init__(self):
        foo_1()
        foo_2()

    def foo_1(self):
        self.a = 0
        self.b = 0

    def foo_2(self):
        self.c = 0

b) Here, it's easy to locate all attributes but is it beautiful ?

class Foo:
    def __init__(self):
        (self.a, self.b) = foo_1()
        self.c = foo_2()

    def foo_1(self):
        a = 0
        b = 0
        return (a, b)

    def foo_2(self):
        c = 0
        return c

In a nutshell, what is your conventions to declare your attributes in a class ?

EDIT:

Of course, it's a simple example and there's no need to improve my code here. Just imagine a complex class with a lot of "small methods" (to divide my code, to improve the readability) called in _init_().

like image 600
Sandro Munda Avatar asked Jan 20 '23 20:01

Sandro Munda


1 Answers

Ideally, your constructor should not call methods: a constructor should not do real work.

If the number of attributes grows out of proportion, you should refactor your class, for example using Extract Class to break your class into several classes, thereby respecting the single responsibility principle.

like image 60
Tommy Avatar answered Jan 30 '23 18:01

Tommy