[英]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.我有两个类(My_class 和 My_class2),它们的功能基本相同,但语法不同。 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.在 class My_class 中,属性 'sum' 和 'fullname' 在构造函数中定义为 None ,然后在调用方法时它们得到它们的值。 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.在 My_class2 中,属性未在 class 中初始定义,但在代码期间,属性是使用方法的返回值在现场创建的。
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;除了这些考虑之外,对于python >= 3.6
,将 class 的所有属性声明到__init__
方法中,允许 class 使用新的compact dict
,该字典共享密钥(跨所有实例) that saves in the order of 20% of the memory needed by instances of the class.这节省了 class 实例所需的 memory 的 20%。
https://youtu.be/p33CVV29OG8?t=2012 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.第一个选项是最好的,因为您可以通过调用获取总和和全名,该调用输入了构建 object 实例所需的其他信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.