About self in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

About self in Python

I have seen that we can do that in our class methods: def __init__(self,value): self = value But the problem is that we cannot add something into a pointer(if we take the base programming language as C++, in this case the pointer is "this" pointer). What is this self actually and what is happening in this methods whenever we use self like that? And also, arr = [2,9] arr1 = [2,9] print(arr is arr1) why the output is False? Thanks

3rd Jun 2018, 3:20 PM
Yusuf
Yusuf - avatar
3 Answers
+ 2
Thank you so much Pedro. I understand second part but still have problems about first part. I know what you wrote above. What I couldn't get what is happening whenever we assign something into self. What is the difference between those two statement: self.value = value self = value ?
3rd Jun 2018, 4:08 PM
Yusuf
Yusuf - avatar
+ 1
First part: self stands for the object: class Cat: def __init__(self, color): self.color = color maxwell = Cat(“white”) Above, the last line stantiates a Cat object and passes “white” as the second (yes, second) argument to its initializer (__init__). (The first argument is the object being built; we dont write it explicitly in the parenthesis). Inside __init__, we take this color string and assign it to one of maxwell’s attribute: his color. Second part: “==“ stands for equality, while “is” stands for identity. The two lists you wrote are equal, but the way you defined them makes them different objects (in the sense that they’re saved in different pieces of memory, despite having the same values). x is y # is equivalent to id(x) == id(y)
3rd Jun 2018, 3:46 PM
Pedro Demingos
Pedro Demingos - avatar
+ 1
class Cat: def __init__(self, color); self = color maxwell = Cat(“white”) In the above, it seems to me that maxwell will end up having the value of the string “white”. Because that’s what self = color should do. At least it makes sense to me. But it would be pointless, and I might be wrong.
3rd Jun 2018, 10:37 PM
Pedro Demingos
Pedro Demingos - avatar