I'm pretty new to programming, and I've looked at a bunch of of other questions/answers for a solution to this, but I'm still confused. Could somebody explain it in a very simple way?
Asked
Active
Viewed 488 times
-1
-
1init is the constructor for a class. Self references the local variables to that object. Note, self is variables to OBJECT, not variables to method. – Fallenreaper Jun 26 '18 at 01:01
-
`__init__` is the function python calls to initialise the object. So you can set it up with any parameters it needs e.g. to assign a `name` parameter to a `Person` object. `self` is just a way to refer to itself. It needs this as you may create multiples of the same object and that is how you refer to the one you are dealing with at that specific moment. These are fundamental concepts in python and trying to learn them piecemeal from web sites will be painful, if you are committed to learning try to get a book, you may even be able to borrow one if you cant afford to buy one. – Paul Rooney Jun 26 '18 at 01:02
-
I saw those, but I still wasn't understanding. I guess something clicked though because it makes more sense to me now. – garfielf Jun 26 '18 at 01:40
1 Answers
0
When you are creating a class, you need to create a constructor. It is what occurs when you create a new instance of your class. In there, you would maybe have your minimum required arguments passed into the object, and do whatever initialization you need for that object to function as designed.
SELF is a reference to the variables defined by the class. Note: It is not a reference to variables defined in the method, though you can define new properties for SELF in the function
class Foo ():
"""This is a dummy class"""
def __init__(self, a, b, c):
self.name = a
self.description = b
self.total = c
def testMethod(self):
print("My name is: {} and my Desciption is: {}".format(self.name, self.description))
For more information, feel free to look up the respective documentation for Classes.
NOTE: for Python 2.7, you need to define a variable object
as an object of Foo, because it extends from object. In 3.X, you dont need this.

Fallenreaper
- 10,222
- 12
- 66
- 129
-
Oh, so if you did something like instance = Foo() then self.name and self.description would basically be the same as instance.name or instance.description? – garfielf Jun 26 '18 at 01:36
-
you are correct. Though, GENERALLY, i try to stay away from dynamic argument assignment like that, and *define* things as private by using: `self.__name` for example. Its not really private, but it is the pythonic standard. I like to create functions which handle arg processing so you dont accidentally feed broken code or variables into a property. – Fallenreaper Jun 26 '18 at 01:53