FAQ: Learn Python: Classes - Self

I think the dictionary comparison is to tell you that in a dictionary, there is no way to guarantee or make certain keys mandatory, something we can do with classes and instance variables.

Unless you create the dictionary through a function that scaffolds one out and takes arguments, not unlike what we did in the dictionary project with Abruptly Goblins. But, I suppose that’s veering into the age-old debate between OOP and functional programming/preferring shared abstractions, which it would be fair enough to say is a bit beyond the scope of the present lesson.

What if i do not declare the attribute “self” ??? (in a method inside a class)

for example here:
image

self is not the attribute, but the instance object. Above, url is the attribute. However, as it is not a global or otherwise defined variable, we can only access it on the instance.

self.url

There is no rule that says we have to name it, self. We can call our instance anything we wish, this, that, instance, etc. Anything we wish so long as it is not reserved. Pythonic convention is to use self as the principal context, and other when we have two instances in the same method.

Bottom line, don’t let this confuse you. self is to Python as this is to JavaScript, although the latter is not optional. We cannot give it any name we wish like we can with self. It is because we introduce self as a parameter of methods that we can call it anything.

1 Like

Why the method inside the Circle class cannot access pi directly and we need to do self.pi? Suppose pi is in the scope of the method and pi is the same for all the instances of the class?

I am kinda confused and any help is greatly appreciated. : )

Since pi is defined within the class, as a class variable we need to distinguish it from a global variable so must prefix it with self. when accessing from within any methods. If we try to access pi directly the interpreter will be looking for it in global scope.

>>> from math import pi as PI
>>> PI
3.141592653589793
>>> pi = int(PI * 1e4) / 1e4
>>> pi
3.1415
>>> pi = round(PI, 4)
>>> pi
3.1416
>>> class Circle:
	pi = 3.14

	
>>> PI
3.141592653589793
>>> pi
3.1416
>>> Circle.pi
3.14
>>> 
1 Like