You are reading the article Working And Examples Of Numpy Zeros_Like Function updated in December 2023 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Working And Examples Of Numpy Zeros_Like Function
Introduction to NumPy zeros_likeWeb development, programming languages, Software testing & others
SyntaxThe syntax for NumPy zeros_like function in Python is as follows:
numpy.zeros_like(arrayname, datatype, memoryorder, subok)where arrayname is the name of the array whose values must be replaced with zeros without a change in the size and shape of the array,
The data type is the data type of the values stored in the array. The default datatype for the given values in the array is float. This parameter is optional.
Memoryorder represents the order in the memory. The subok represents a Boolean value that is true if the array returned by using zeros like function is a subclass of the input array and false if the returned array is the same as the original array. This parameter is optional.
Working of NumPy zeros_like function
Whenever we have an array whose values must be replaced with all zeroes and the array size and shape must be retained as the original array, we make use of a function called zeros like function in numpy.
The zeros like functions take four parameters arrayname, datatype, memoryorder, and subok, among which the datatype and subok parameters are optional.
datatype represents the data type of the value stored in the array whose name is represented by the first parameter arrayname.
memoryorder represents the order in the memory.
subok represents a Boolean value which is true if the array returned by using zeros like function is a subclass of the input array and false if the returned array is the same as the original array.
Examples of NumPy zeros_likeDifferent examples are mentioned below:
Example #1Python program to demonstrate NumPy zeros like function to create an array using array function in numpy and then using zeros like function to replace the elements of the array with zeros:
#importing the package numpy import numpy as n #Creating an array by making use of array function in NumPy and storing it in a variable called orgarray orgarray = n.array([[1,2],[3,4]]) #Displaying the elements of orgarray followed by one line space by making use of n print ("The elements of the given array are:") print (orgarray) print ("n") #using zeros like function of NumPy and passing the created array as the parameter to that function to replace all the elements of the array with zeros and store it in a variable called zerosarray zerosarray = n.zeros_like(orgarray, float) #Displaying the array consisting of all zero elements print ("The array with all its elements zero after using zeros like function is as follow:") print (zerosarray)Output:
In the above program, we are importing the package numpy, which allows us to make use of the functions array and zeros_like. Then we are creating an array called orgarray by making use of the array function in numpy. Then the elements of the array orgarray are displayed on the screen. Then we are making using zeros_like function, and the newly created array orgarray is passed as a parameter to the function to convert all the elements of the array to zeros without changing the size and shape of the array, and the resulting array is stored in a variable called zerosarray. Finally, the elements of the zerosarray are displayed on the screen.
Example #2Python program to demonstrate NumPy zeros like function to create an array using array function in numpy and then using zeros like function to replace the elements of the array with zeros:
#importing the package numpy import numpy as n #Creating an array by making use of array function in NumPy and storing it in a variable called orgarray orgarray = n.array([[5,6],[7,8]]) #Displaying the elements of orgarray followed by one line space by making use of n print ("The elements of the given array are:") print (orgarray) print ("n") #using zeros like function of NumPy and passing the created array as the parameter to that function to replace all the elements of the array with zeros and store it in a variable called zerosarray zerosarray = n.zeros_like(orgarray, int) #Displaying the array consisting of all zero elements print ("The array with all its elements zero after using zeros like function is as follow:") print (zerosarray)Output:
In the above program, we are importing the package numpy, which allows us to make use of the functions array and zeros_like. Then we are creating an array called orgarray by making use of the array function in numpy. Then the elements of the array orgarray are displayed on the screen. Then we are making using the zeros_like function. The newly created array orgarray is passed as a parameter to the function to convert all the elements of the array to zeros without changing the size and shape of the array. The datatype int is also passed as the parameter, which displays the zeros in the resulting array as integer values. Then the resulting array is stored in a variable called zerosarray. Finally, the elements of zerosarray are displayed on the screen.
ConclusionIn this tutorial, we understand the concept of NumPy zeros like function in Python through definition, the syntax of zeros like function, and the working of zeros like functions through programming examples and their outputs.
Recommended ArticlesThis is a guide to NumPy zeros_like. Here we discuss the Working of NumPy zeros_like function and Examples along with the codes and outputs. You may also look at the following articles to learn more –
You're reading Working And Examples Of Numpy Zeros_Like Function
Working Of Bless() Function In Perl With Examples
Introduction to Perl bless function
Web development, programming languages, Software testing & others
Working of bless() function in Perl with examplesIn this article, we will discuss a built-in function where to make the program understand that the variable can be made an object of a particular class in Perl, where this function is known as the bless() function. Unlike in other programming languages, Perl creates an object similar to creating or declaring variables. Therefore the Perl programming language provides a built-in function called bless() function, which makes the variable look like an object of the particular class that it belongs to.
Now let us see the syntax and examples of how the bless() function works in the below example.
Syntax:
bless var_ref, class_name;Parameters:
var_ref: this parameter refers to the variable as an object of the class whose class name is specified.
class_name: This parameter specifies the class name to which the object is created by marking the variable reference as an object of this class specified in this parameter.
This function can take only var_ref as an argument also, and this function returns the reference of the marked variable as a reference to an object blessed into a particular or specified class name as specified in the arguments passed to the function.
ExamplesNow let us see a simple example of demonstrating the bless() function in the below section.
Example #1 use strict; use warnings; print "Demonstration of bless() function in Perl."; print "n"; print "n"; package student_data; sub stud { my $class_name = shift; my $var_ref = { }; print "The bless() function is now implemented:"; print "n"; bless $var_ref, $class_name; return $var_ref; } print "Object creation"; print "n"; print "n"; my $info = stud student_data("Alen","Python",32); print "The student's name is :"; print "n"; print "n"; print "The course name student taken is:"; print "n"; print "n"; print "The student's age is :"; print "n"; print "n";Output:
In the above program, we can see we have defined class “stud” using a keyword package in Perl. Then we created a subroutine to print the student’s details. In this variable, we are referring each variable to the class name using the variable reference to object creation and class name as arguments in the bless() function in the above program. Then we are printing each value of the objects created.
Now we will see bless function taking only one argument and two arguments in the example below.
Example #2 use strict; use warnings; print "Demonstration of bless() function in Perl."; print "n"; print "n"; package student_data; sub stud { my $class_name = shift; my $var_ref = { }; print "The bless() function is now implemented:"; print "n"; bless $var_ref; return $var_ref; } package Employee; sub emp { my $class2 = shift; my $var_ref2 = { }; bless $var_ref2, $class2; return $var_ref2; } print "Object creation"; print "n"; print "n"; print "Bless function takes only one argument:"; print "n"; print "n"; my $info = stud student_data("Alen","Python",32); print "The student's name is :"; print "n"; print "n"; print "The course name student taken is:"; print "n"; print "n"; print "The student's age is :"; print "n"; print "n"; print "Bless() function takes two argument:"; print "n"; print "n"; my $per_info = emp Employee("Ram", "Shukla", 343); print "The employee's name is :"; print "n"; print "n"; print "The employee's second name student taken is:"; print "n"; print "n"; print "The employee's employee number is :"; print "n"; print "n";Output:
In the above program, we can see we have declared two classes “student_data” and “Employee” wherein the class “Student_data” we have defined function bless() with the single argument so when the variables reference is only passed, it will by default, take only the values of its current class but not of the “employee” class.
ConclusionIn this article, we conclude that the bless() function is a built-in function in Perl for marking the variables reference to object creation which belongs to the particular class with its class name specified as an argument in the bless() function. In this article, we have seen examples of bless() function taking two arguments and what happens if there are two classes and the class name is not specified as an argument in the function, which will, by default, take the current class name.
Recommended ArticlesThis is a guide to Perl bless. Here we discuss the introduction and Working of bless() function in Perl with examples for better understanding. You may also have a look at the following articles to learn more –
How Outer Function Works In Numpy?
Introduction to NumPy Outer
Web development, programming languages, Software testing & others
SyntaxOuter() is one of the predefined functions of the Numpy library, and mainly, it’s used for vector and matrix calculations; its basic syntax is as follows below.
import numpy as first x=first.ones() y=first.linspace() z=first.outer(x,y) print (z)Above basic Python code, we have imported the numpy packages in the Python script, and it has called the pre-defined methods of the package. The vector has rows and columns for all the dimensions, releasing both 2D and 3D vectors in matrix multiplications.
How outer Function works in NumPy?In the Numpy library, the outer is the function or product of two coordinate vectors in the matrix calculations. We use more than one vector with dimensions like any variables, and their variables are calculated using the “x” multiplication operator for calculating matrix outputs. If suppose we use the tensor type of datas like a multidimensional array of numbers, then the outer function will give the tensor as a result. It is also known and defined as tensor algebras. The outer function is also known as the outer product, and the tensor is also referred to as the tensor product. The outer function used dot products, and Kronecker products also used standard matrix multiplications.
The Numpy arrays have used both single and multi-dimensional arrays if we can pass the Python list to the arrays method in single or one-dimensional arrays. And if we pass the list of lists packages in the arrays method in multi or two-dimensional arrays. The matrix array multiplication in every inner list and the outer lists becomes the rows and columns if the number of columns equals the number of elements in each inner list. When we use arrays in the Numpy, it has some default and important pre-defined methods, which are arrange(), zeros(), and ones(), etc, while creating the NumPy arrays. Also, if we use the arrays, it takes the arguments like start index, end index, and some linearly-spaced types of numbers that can be the specified ranges. The index values are different depending on the application requirement.
Examples of NumPy OuterHere are the following examples as mentioned below.
Example #1 import numpy as np p = np.array([3, 6, 8], float) q = np.array([4, 7, 13], float) print("The Calculation of Matrixes and vectors are.") print("p:") print(p) print("q:") print(q) print("The Outer function used in the p and q are:") print(np.outer(p, q))Output:
Example #2Code:
import numpy as np p = np.ones(6) q = np.linspace(-5, 3, 7) r = np.outer(p, q) print (r) x = [5, 9] y = [2, 6, 4] z = np.outer(x, y) print(z)Output:
Example #3 import numpy as np p = np.array([[4, 3, 2, 1, 16], [-7, 4, 3, 6, 15], [-5, 2, 19, 11, 26]]) y = [2, 6, 4] print(p[:3, :7]) print(p[:6,]) print(p[:,5]) print(A[:, 4:8]) z = np.outer(p, y) prPostint(z)Output:
In the above three examples, we described the outer function in different areas, as well as the Numpy library has used many other different methods like slicer(), inner(), ones(), etc. If the user inputs must be entered in multiple areas simultaneously, the inputs are validated in both the front and back ends. Depending on the application requirements, the inputs can be in number formats such as integer, float, or decimal point. When using the Numpy packages, it becomes essential to validate user inputs due to their specific design for integer formats and utilization of arrays and vectors for matrix calculations.
ConclusionIn this article, we have discussed some important points regarding the Numpy packages and their method, especially in the outer() function. So in the latest and future technology purpose, these Numpy packages and their methods are an important part of the technology trends.
Recommended ArticlesThis is a guide to NumPy Outer. Here we discuss How outer function works in NumPy and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –
Examples Of Excel Vba Dateadd Function
Excel VBA DateAdd
VBA DateAdd is a function which performs addition or subtraction of time/date intervals. This will return date by adding or subtracting a specified time interval. It is quite difficult to deal with date and time when you do some calculations on it. But in our daily work, it is an essential type of data that we may use. Comparison, addition, subtraction between different dates are some familiar operations that we do.
Formula For DateAdd function in Excel VBA
Watch our Demo Courses and Videos
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
The formula for VBA DateAdd function is very simple in format.
Let’s see what are the parameters used in the Excel VBA DateAdd function.
Interval: This can be a time/date interval that you want to add or subtract. This represents what kind of value you wish to add or subtract. This can be a component of date or time like days, month, etc. The scope of intervals is given below.
Number: Is the number of intervals you want to add. Use a positive number to add the interval with the given date and negative value to subtract the interval from the date.
Date: The date to which you want to add/subtract the interval. Operations will be performed on this date and return date as output.
Examples of Excel VBA DateAdd FunctionBelow are the different examples of DateAdd Function in Excel VBA:
You can download this VBA DateAdd Excel Template here – VBA DateAdd Excel Template
Example #1 – Add DateLet’s see how to add a particular number with the given date using VBA DateAdd Function.
We need to find the date after adding ’10’ days with the date ‘25/10/2023’
Start sub procedure with a name. Here we created a sub procedure named ‘adddate’.
Code:
Sub
adddate()End Sub
Create a variable as date datatype, variable name is currentdate.
Code:
Sub
adddate()Dim
currentdateAs Date
End Sub
We are going to store the result in this variable currentdate.
We want to add ‘10’ days with ‘25/10/2023’. So the number of days want to add is 10. And the interval is ‘d’ and the number is 10.
So let’s apply the VBA DateAdd function as below.
Code:
Sub
adddate()Dim
currentdateAs Date
currentdate = DateAdd("d", 10, "25/10/2023")End Sub
After applying the formula to the variable let’s use a message box to print the result.
Code:
Sub
adddate()Dim
currentdateAs Date
currentdate = DateAdd("d", 10, "25/10/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
Run the code by pressing F5. The result will be shown as
You can see the result as shown above.
Example #2 – Add Months
To add months with the given date the interval needs to change as “m”.
Add ‘2’ with the date “15/2/2023”. The code can be written as below.
Code:
Sub
addmonth()Dim
currentdateAs Date
currentdate = DateAdd("m", 2, "15/2/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
The output date will be changed as below.
Example #3 – Add YearTo add years with the given date the below code can be used.
The interval should be” yyyy”
Add 4 years with’20/2/2023’
Code:
Sub
addyear()Dim
currentdateAs Date
currentdate = DateAdd("yyyy", 4, "20/2/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
The result will be as below. The variable currentdate will return ‘20/2/2023’
Example #4 – Add Quarter
While adding quarter, three months will be added to the date since the quarter if 12 months is 3.
The interval should be mention as “Q”, the number given in the formula specifies how many quarters should be added. For example, DateAdd(“Q”,2, ”22/5/2023”) number of quarters is 2 so 6 months will be added.
To add 2 quarters with ‘22/5/2023’ below code can be used.
Code:
Sub
addquarter()Dim
currentdateAs Date
currentdate = DateAdd("Q", 2, "22/5/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
The result will be as below.
Example #5 – Add Seconds
You can add time along with date displayed. To get this mention the interval as “s” which indicates seconds.
To display five seconds with date ‘28/3/2023’ can use the below formula.
Code:
Sub
addseconds()Dim
currentdateAs Date
currentdate = DateAdd("s", 5, "28/3/2023") MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")End Sub
While showing the output with date seconds will be displayed.
Example #6 – Add Weeks
To add a number of weeks with the given date, use the interval as “WW”
Code to find the date after the given number of weeks from’27/03/2023’
Code:
Sub
addweek()Dim
currentdateAs Date
currentdate = DateAdd("WW", 2, "27/3/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
The output will be the date after 2 weeks.
Example #7 – Add Hours
To get a particular time with a date this is used.
In interval mention the “h” and also change the format of the output.
The code to get the hours printed with a date is.
Code:
Sub
addhour()Dim
currentdateAs Date
currentdate = DateAdd("h", 12, "27/3/2023") MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")End Sub
The result will be shown with time in hh:mm:ss.
Example #8 – How to Subtract Weeks using VBA DateAdd Function?Similar to addition, subtraction can also perform using VBA DateAdd function. The numbers specified as positive integers along with the formula. To perform subtraction, use these numbers as negative integers. For example, change the formula as below.
DateAdd (interval, - number, date)By using the above method will try to find the day subtracting three weeks from ‘28/3/2023’
Create a subprocedure as subdate.
Code:
Sub
subdate()End Sub
Define a variable to store the result. Currentdate is a variable as date type to assign the final result.
Code:
Sub
subdate()Dim
currentdateAs Date
End Sub
To subtract three weeks from ‘28/3/2023’ will apply the formula. DateAdd(“ww”, -3, “28/3/2023”)
Code:
Sub
subdate()Dim
currentdateAs Date
currentdate = DateAdd("ww", -3, "28/3/2023")End Sub
‘-3’ indicates the subtraction “ww” is the interval since we want to operate on weeks.
The formula is applied and the result is stored in currentdate.
Code:
Sub
subdate()Dim
currentdateAs Date
currentdate = DateAdd("ww", -3, "28/3/2023") MsgBox Format(currentdate, "dd-mm-yyyy")End Sub
The result after subtracting three weeks from the given date is displayed below.
Things to Remember
The interval and date mentioned in the formula will be given within a double quotation.
If you use weekdays interval” w” it will work similarly to the interval day “d” since the weekday calculates 1=Sunday, 2=Monday, etc. in So it will count the holidays even you use weekdays.
The out will be displayed according to the date format settings on your system. Use format along with a message box to print the result in the format you want.
Within the VBA DateAdd function use the number as negative to perform subtraction among dates.
Recommended ArticlesThis is a guide to Excel VBA DateAdd Function. Here we discuss the examples of VBA DateAdd function to add & subtract days, months & years from the given date along with practical examples and downloadable excel template. You can also go through our other suggested articles –
How Does Vectorize Function Work In Numpy?
Introduction to NumPy Vectorize
Python provides different functions to the users. To work with vectorizing, the python library provides a numpy function. The NumPy vectorize accepts the hierarchical order of the numpy array or different objects as an input to the system and generates a single numpy array or multiple numpy arrays. After successive multiple arrays of input, the NumPy vectorize evaluates pyfunc like a python map function, and it helps to define numpy rules. We use numpy vectorization instead of a loop to increase speed. Arrays play a major role in data science, where speed matters. Basically, numpy is an open-source project. In python, numpy is faster than the list. Therefore, processing and manipulating can be done efficiently.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax of NumPy VectorizeThe syntax for NumPy Vectorize is as follows:
vectorize_funcunction = np.vectorize (function, parameter 1, parameter 2….. parameter N)In the above syntax, vectorize_function is a function name, np.vectorize is a numpy class, and function is a user-defined function with parameters. The parameters which we are using in the numpy vector as below.
Different Parameters of Numpy vectorize are as follows.
1. pyfunc: It is used to define the function of python as well as the method, and it must be required. Therefore, it is a callable parameter.
2. otypes: The otypes mean output data type, and it is optional. In otypes, it should be specified as either a list of data types specified or a string of type code characters. For each output, there must be one data specified.
3. doc: The doc is an optional parameter to the docstring. If there is none in doc, then docstring will be pyfunc_doc_str.
4. excluded: This is an optional parameter. This parameter consists of either a set of strings or integers representing the positional or keyword arguments for the functions that will not be vectorized. A set of strings or integers will be passed directly to pyfunc unmodified.
5. cache: The cache is an optional parameter. It will cache the first function call, which generally determines the number of outputs if True and otypes are not given.
How does the vectorize function work in NumPy?
We must install Python on your system.
We must install numpy using the pip command.
We required basic knowledge about Python.
We required basic knowledge about arrays.
We can perform different operations using the numpy vectorize function.
Let’s see how we can implement a numpy vectorize function on an array. But, first, we see what is the difference between vectorizing and non-vectorize implementation.
1. Vectorize ImplementationIt is mainly related to matrices. In vectorize implementation, we execute huge algorithms like machine learning algorithms and neural language algorithms.
Example
import numpy as np import time no = 100000 x = np.random.random(no) y = np.random.random(no) start = time.time() z = np.dot(x,y) end = time.time() print("Vectorize :" + str((end-start)*1000)+ 'ms')Explanation
In the above example, we implemented the numpy vectorize function using an array. In this program, we used two arrays, x, and y, with random numbers, and then we used dot product means the multiplication of x and y arrays. Also, we have calculated the total execution time of the x and y array using vectorize. Thus, the vectorize function takes minimum time for execution. Illustrate the end result of the above declaration by using the use of the following snapshot.
2. Non-Vectorize ImplementationIn this implementation, we use a loop for implementation purposes non-vectorize implementation takes more time to execute as compared to vectorize implementation.
Example:
import numpy as np import time no= 100000 x=np.random.random(no) y=np.random.random(no) start = time.time() z=0 for i in range(no): z += x[i] + y[i] end=time.time() print("Loop :" + str((end-start)*1000)+ 'ms')Explanation
In the above example, we implemented a non-vectorize numpy. In this example, we used a loop for implementation. Here we have used Loop instead of Vectorize. As a result, the non-vectorize takes more time. Illustrate the end result of the above declaration by using the use of the following snapshot.
Example: numpy vectorize function
import numpy as np def func1(c, d): return c - d else: return c + d vfun = np.vectorize(func1) z=vfun([4, 3, 5, 2], 1) print(z)Explanation:
In this example, we have implemented numpy vectorization. We have defined a vectorize function in which m and n are arguments. The Vectorize function used in the above example reduces the length of code. In this example, vfun directly performs the operation on arrays. Illustrate the end result of the above declaration by using the use of the following snapshot.
import numpy as np def func1(p, q): vecfunc.__doc__ vecfunc = np.vectorize(func1, doc="welcome to python") a=vecfunc.__doc__ print(a)Explanation:
For vectorization, the docstring is obtained from the input function unless the docstring is specified. Illustrate the end result of the above declaration by using the use of the following snapshot.
Example: Excluded
import numpy as np def pval(x, y): _x = list(x) res = _x.pop(0) while _x: res = res*y + _x.pop(0) return res vect_pval = np.vectorize(pval, excluded=['x']) z=vect_pval(x=[2, 4, 5], y=[1, 2]) print(z)Explanation:
The excluded is used to stop vectorizing over some arguments. In this example, we implement polynomials as in polyval. Finally, illustrate the end result of the above declaration by using the use of the following snapshot.
In a similar way, we can implement remaining parameters like otype and signature and perform different operations with the help of numpy vectorize.
ConclusionWe hope from this article you have understood about the numpy vectorize function. From the above article, we have learned the basic syntax numpy vectorize function. We have also learned how we can implement them in Python with different examples of each parameter. With the help of the vectorizing function, we reduce the execution time of the algorithm. From this article, we have learned how we can handle numpy vectorize in python.
Recommended ArticlesThis is a guide to NumPy Vectorize. Here we discuss How does the vectorize function work in NumPy and Examples along with the Explanation. You may also look at the following articles to learn more –
Working Of Mixin In Typescript With Examples
Introduction to TypeScript Mixins
Web development, programming languages, Software testing & others
Working of Mixin in Typescript with ExamplesThere is no particular syntax for writing mixin class as it is an extra class written to overcome the single inheritance problem, which means there is no restriction for extending a single class one at a time. Using mixin class is used in building simple partial classes, and this mixin class returns a new class. Therefore, the syntax of the mixin class cannot be defined exactly as it is a class that can take a constructor to create a class that has the functionalities of the constructor by extending the previous class and then returns a new class.
Suppose if we have two classes X and Y where class X wants to get the functionality of class Y, and this can be done using extending class X extends class Y, but in Typescript, mixins are used to extend the class Y, and therefore this function Y takes class X, and therefore it returns the new class with added functionality, and here the function Y is a mixin. In general, the mixin is a function that takes a constructor of the class to extend its functionality within the new class that is created, and this new class is returned.
The exact working of mixin can be demonstrated as a process of mixing multiple classes to a single target class, and this is done by using the “implement” keyword in Typescript for the target mixin class, which also uses some generic helper functions which helps to copy the properties of each mixin to the target mixin. But we cannot use interfaces as it can only extend the members of the class but not their implementations. Therefore, TypeScript provides mixins that help to inherit or extend from more than one class, and these mixins create partial classes and combine multiple classes to form a single class that inherits all the functionalities and properties from these partial classes.
Example of TypeScript MixinsDifferent example are given below:
Example #1Code:
console.log(" Demonstration of mixin using extends in Typescript") class Courses { name = ""; x = 0; y = 0; constructor(name: string) { this.name = name; } } return class Scaling extends Base { _scale = 1; setScale(scale: number) { this._scale = scale; } get scale(): number { return this._scale; } }; } const Institute = Scale(Courses); const numcourse = new Institute("Educba"); numcourse.setScale(3); console.log(numcourse.scale);In the above program, we are first creating class “Courses” which we are trying to scale the number of courses in the institute but to extend this class property we are using mixin concept that is first take a constructor as to make mixin extend the class “Courses” with new functionalities and the constructor is defined using “constructor” keyword. Then to extend the class “Courses”, we need to use the keyword “extends”, which is done n the function Scale where we are extending the constructor of the class to create a new class and return that class. The output of the code can be seen in the screenshot, where we are inheriting the property setscale() by extending the constructor and creating a new class named “Institute”, which is extended by the “Course” class.
Now let us see another example where it will take multiple classes and how the mixin works.
Example #2 console.log(" Demonstration of mixin in Typescript ") class Mathfunc{ calculate(): void { console.log("The math formula is getting executed"); } } class Variables { display(): void { console.log("The variables given are calculated and display the result"); } } class Add implements Mathfunc, Variables { a: number; b: number; constructor(a, b) { this.a = a; this.b = b; } res(): number { return this.a + this.b; } display(): void { } calculate(): void { } } function applyMixins(derivedCtor: any, baseCtors: any[]) { Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name)); }); }); } applyMixins(Add, [Mathfunc, Variables]); let p: Add = new Add(9, 7); p.calculate(); p.display(); let r = p.res(); console.log("The Additin of two given numbers is as follows:"); console.log(r);Output:
In the above program, we can see we have classes “mathfunc”, “variables”, and “Add” where t display we are just providing “implements” keyword to extend the class properties. We are providing empty implementations which mixin helper functions will later replace. Therefore this mixin created iterate through properties of the base classes and then copy all these properties from these single classes into one single target class, and this done in the function apply mixin in the above program. Therefore we are trying to calculate the sum of two numbers where we have created a constructor with two different variables, and the result is displayed using the res() function, which returns the sum.
ConclusionThis article concludes with a demonstration of mixin in typescript where we saw how mixin works with keyword “extends” and “implements”. In this article, we saw an example of demonstrating the mixin which supports single inheritance by using these keywords in the program. We should also note that it may take much time in compiling the above approaches.
Recommended Articles
We hope that this EDUCBA information on “TypeScript Mixins” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Update the detailed information about Working And Examples Of Numpy Zeros_Like Function on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!