|
| 1 | +''' |
| 2 | + |
| 3 | +<P1> |
| 4 | + |
| 5 | +self is not a keyword. self refers to the current object being executed. |
| 6 | +''' |
| 7 | + |
| 8 | +class Mobile: |
| 9 | + def __init__(self, price, brand): |
| 10 | + print("Id of self in constructor", id(self)) |
| 11 | + self.price = price |
| 12 | + self.brand = brand |
| 13 | + |
| 14 | +mob1=Mobile(1000, "Apple") |
| 15 | +print("Id of mob1 in driver code", id(mob1)) |
| 16 | + |
| 17 | +mob2=Mobile(1000, "Apple") |
| 18 | +print("Id of mob2 in driver code", id(mob2)) |
| 19 | + |
| 20 | + |
| 21 | + |
| 22 | +''' |
| 23 | + |
| 24 | +<P2> |
| 25 | + |
| 26 | +We have already seen that reference_variable.attribute_name creates an attribute for that object. |
| 27 | +By using self.attribute_name and assigning a value we are creating attributes to the current object. |
| 28 | +The best practice is to create attributes inside the constructor. |
| 29 | +''' |
| 30 | + |
| 31 | +class Mobile: |
| 32 | + def __init__(self, price, brand): |
| 33 | + print("Id of self in constructor", id(self)) |
| 34 | + self.price = price |
| 35 | + self.brand = brand |
| 36 | + |
| 37 | +mob1=Mobile(1000, "Apple") |
| 38 | +print("Id of mob1 in driver code", id(mob1)) |
| 39 | + |
| 40 | +mob2=Mobile(1000, "Apple") |
| 41 | +print("Id of mob2 in driver code", id(mob2)) |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +''' |
| 46 | + |
| 47 | +<P3> |
| 48 | + |
| 49 | +Attributes can be created only by using the self variable and the dot operator. |
| 50 | +Without self we are only creating a local variable and not an attribute. |
| 51 | +''' |
| 52 | + |
| 53 | +class Mobile: |
| 54 | + def __init__(self): |
| 55 | + print ("Inside the Mobile constructor") |
| 56 | + self.brand = None |
| 57 | + brand = "Apple" #This is a local variable. |
| 58 | + #Variables without self are local and they dont |
| 59 | + #affect the attributes. |
| 60 | + |
| 61 | + #Local varaibles cannot be accessed outside the init |
| 62 | + #Using self creates attributes which are |
| 63 | + #accessible in other methods as well |
| 64 | + |
| 65 | +mob1=Mobile() |
| 66 | +print(mob1.brand)#This does not print Apple |
| 67 | +#This prints None because brand=Apple creates |
| 68 | +#a local variable and it does not affect the attribute |
0 commit comments