Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fe52531

Browse files
authored
It contains 3 Parts
1 parent f684bc5 commit fe52531

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎docs/OOPS/What_is_self(full).py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /