-
Notifications
You must be signed in to change notification settings - Fork 2
/
11_classes.py
80 lines (63 loc) · 2.43 KB
/
11_classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#This is a python script to demonstrate classes
#This is a class
#Classes are used to create objects
class MyClass:
#This is a docstring
#Docstrings are used to describe a class
"""This class prints Hello and the name passed as a parameter"""
#This is a class variable
#Class variables are variables that are shared by all objects of the class
classVariable = "Hello World"
#This is a constructor
#Constructors are used to initialize the object
def __init__(self, name):
#This is an instance variable
#Instance variables are variables that are unique to each object of the class
self.name = name
#public variables are accessible from outside the class
self.publicVariable = "Hello World"
#protected variables are accessible from within the class and its subclasses
self._protectedVariable = "Hello World"
#private variables are accessible only from within the class
self.__privateVariable = "Hello World"
#This is a method
#Methods are functions that are defined inside a class
def myMethod(self):
print("Hello " + self.name)
#This is a static method
#Static methods are methods that are bound to a class and not the object of the class
@staticmethod
def myStaticMethod():
print("Hello World")
#This is a class method
#Class methods are methods that are bound to the class and not the object of the class
@classmethod
def myClassMethod(cls):
print("Hello World")
#This is a property
#Properties are used to define getter, setter and deleter methods
@property
def myProperty(self):
#This is a getter method
return self.__privateVariable
@myProperty.setter
def myProperty(self, value):
#This is a setter method
self.__privateVariable = value
@myProperty.deleter
def myProperty(self):
#This is a deleter method
del self.__privateVariable
#This is a magic method
#Magic methods are used to define the behavior of operators
def __add__(self, other):
return self.name + other.name
#This is an object
#Objects are instances of a class
obj = MyClass("GDSC")
#This is an object method call
#Object method calls are used to call a method of an object
obj.myMethod()
#This is an object variable access
#Object variable accesses are used to access a variable of an object
print(obj.name)