简体   繁体   中英

Creating new attribute inside or outside of a class

I have two classes (My_class and My_class2) that do basically the same, but with different syntax. I would like to know which options is best.

class My_class():
    def __init__(self, int1, int2, str1, str2):
        self.int1 = int1
        self.int2 = int2
        self.str1 = str1
        self.str2 = str2
        self.sum = None
        self.fullname = None

    def add_ints(self):
        self.sum = self.int1 + self.int2

    def concat_strings(self):
        self.fullname = self.str1 + ' ' + self.str2


class My_class2():
    def __init__(self, int1, int2, str1, str2):
        self.int1 = int1
        self.int2 = int2
        self.str1 = str1
        self.str2 = str2

    def add_ints2(self):
        return self.int1 + self.int2

    def concat_strings2(self):
        return self.str1 + ' ' + self.str2



obj1 = My_class(1, 2, 'Peter', 'Philips')

obj1.add_ints()
obj1.concat_strings()

print(obj1.sum, obj1.fullname)



obj2 = My_class2(10, 20, 'John', 'Norton')

obj2.sum = obj2.add_ints2()
obj2.fullname = obj2.concat_strings2()

print(obj2.sum, obj2.fullname)

In class My_class, the attributes 'sum' and 'fullname' are defined as None in the constructor and later on they get their values when the method is called. In My_class2 the attributes are not defined inicialy in the class, but during the code, the attributes are created on the spot with the return values of the methods.

Thank you

Really depends on your use case, but I think first option is nicer. Or an even better way:

class My_class():
    def __init__(self, int1, int2, str1, str2):
        self.int1 = int1
        self.int2 = int2
        self.str1 = str1
        self.str2 = str2
        self.sum = self.add_ints()
        self.fullname = self.concat_strings()

    def add_ints(self):
        return self.int1 + self.int2

    def concat_strings(self):
        return self.str1 + ' ' + self.str2

Arguably, method one offers a better organization and readability of the code; both have their importance.

Outside of these considerations, for python >= 3.6 declaring all the attributes of a class into the __init__ method allows the class to use the new compact dict which shares the keys (attributes names) across all instances; that saves in the order of 20% of the memory needed by instances of the class.

https://youtu.be/p33CVV29OG8?t=2012

The first option is the best due to the fact you can obtain the sum and the full name with a call that has in input the other infromation that are required for building the instance of object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM