Self is merely a conventional name for the first argument of a method inside a class. A method defined as meth(self, a, b, c)
should be called as x.meth(a, b, c)
for some instance x of the class in which the definition occurs; the called method will think it is called asmeth(x, a, b, c)
.
In python all the methods and variables are public by default. Any variable or method with a double underscore “__” prefix is considered as private. Private names dost not exist outside the class in which it is defined.
class A:
def __init__(self, n):
self.__privatevar = n
def __double(self):
return 2*self.__privatevar
def print_double(self):
print(self.__double())
a = A(5)
a.print_double()
print(a.__privatevar)
print(a.__double())
Python supports name mangling technique. Any identifier of the form __spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with _classname_spam
, where classname is the current class name with leading underscore(s) stripped.
class A:
def __foo(self):
return ('yes')
a = A()
print(A.__dict__.keys())
print(a._A__foo())
Class variables are dependent on class. These are created outside the methods of a class and same for all instances.
Instance variables are created with a reference with the instance. They are generally created by assignment to self attributes in a class’s methods.
Class attributes are attributes which are owned by the class itself. They are shared by all the instances of the class. They have the same value for every instance.
Built-in class attributes are the attributes which are automatically created by python with a class. Example: __dict__, __doc__, __name__, __module__ , __bases__.
Method overloading is the ability of a class to have multiple methods of same name with different arguments. Python does not support method overloading. Python can’t have more than one method with same name but here one method can be called with different data types and different number of arguments.
MRO is method resolution order, the order in which inheritance searches classes in a new-style class tree.