Course Discount

Search

Selenium And Its Salient Features

Selenium is an open source web app automation tool by ThoughtWorks (IT outsourcing company). It has 4 components. Out of which one component i.e. Selenium Remote Control was developed by a Jason Huggins team in 2004. It was primarily developed in DHTML/Javascript when they were working on time and expense application written in Python programming language. Later, Simon Stewart has developed a new component that is called as Webdriver in 2006 to overcome the disadvantages faced in Selenium Remote Control. And post that Selenium Remote Control and Webdriver were merged together and developed Selenium Webdriver. They have named this tool as Selenium based on a chemical element in Chemistry which is used to destroy Mercury chemical element.  Mercury tool which is now called as UFT was the most popular automation tool. Selenium has 4 different components that is: Selenium IDE (Integrated Development Environment) Selenium 1.0 (Also called as Remote Control) Selenium 2.0/3.0 (Also called as Webdriver) Selenium GRID Latest version of selenium is 3.4.0 which can be downloaded from https://www.seleniumhq.org/download/ Selenium supports multiple operating systems, multiple browsers and multiple languages. It gives you flexibility to choose the language in which you have expertise. Following is the list: Multiple Programming Languages : Java, Python, PHP, Ruby, Perl, JavaScript Multiple Operating Systems : Android, iOS, Windows, Linux, Mac, Solaris Multiple Browsers : Chrome, Internet Explorer, Edge, Opera, Safari etc Selenium Tool is known for its performance and execution speed. Let’s discuss about the different components of Selenium: 1)Selenium IDE : It is a record and play tool and a plugin of firefox. This plugin is used to create prototypes of tests. Following are the features of this tool: Easy to install Test Scripts are created by just click on record button Can record, edit and debug scripts Simplest way to learn Selenium syntax. Test Scripts can be imported in multiple languages like Python with Remote Control, Java with Webdriver, Java with Remote Control, Ruby with Remote Control etc This plugin can be downloaded from following URL: https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/ 2)Selenium 1.0 (Remote Control) : This was the first component developed in Selenium Suite. Selenium became famous because of this component. It works in following manner: 1) Using this component, we write test scripts which interacts with Selenium Remote Control Server. 2) Server interprets the code and converts it into javascript and further injected into the browsers. 3) Javascript gets executed at the browser and response is sent back to the server which forwards it to the user. There were many drawbacks in this tool that is: Confusing commands. Remote Control Server acts as a mediator which makes its execution slower. Use of Javascript Selenium Webdriver (2.0/3.0) : After Selenium RC, Webdriver has come which make its architecture more simpler. Now, there is no server. Test Scripts interact directly with the browser. The execution is much faster compared to Selenium Remote Control. Selenium Commands were segregated in different classes which become easy for end user to remember and to implement. Last year, Selenium has launched a new version that is 3.0 which is much lighter than Selenium 2.0. There are not much change done which impact the end user but multiple were done at the backend. Syntax for loading Firefox has been changed to following: System.setProperty(“webdriver.gecko.driver”,”path to gecko driver”); Webdriver driver = new FirefoxDriver; Selenium Gecko Driver can be downloaded from following URL, the latest version for Gecko Driver is 0.16.1: https://github.com/mozilla/geckodriver/releases Selenium GRID : It is used for parallel testing. This component enable us to execute automation framework on different machines placed at different location. However, all the machines should be connected on a Local Area Network. It can be used with Selenium Remote Control as well as with Selenium Webdriver. Please note that Selenium Remote Control classes have been deprecated now. So, we couldn’t use this component with Selenium Remote Control.
Rated 4.0/5 based on 1 customer reviews

Selenium And Its Salient Features

730
Selenium And Its Salient Features

Selenium is an open source web app automation tool by ThoughtWorks (IT outsourcing company). It has 4 components. Out of which one component i.e. Selenium Remote Control was developed by a Jason Huggins team in 2004. It was primarily developed in DHTML/Javascript when they were working on time and expense application written in Python programming language. Later, Simon Stewart has developed a new component that is called as Webdriver in 2006 to overcome the disadvantages faced in Selenium Remote Control. And post that Selenium Remote Control and Webdriver were merged together and developed Selenium Webdriver.

They have named this tool as Selenium based on a chemical element in Chemistry which is used to destroy Mercury chemical element.  Mercury tool which is now called as UFT was the most popular automation tool.

Selenium has 4 different components that is:

  • Selenium IDE (Integrated Development Environment)
  • Selenium 1.0 (Also called as Remote Control)
  • Selenium 2.0/3.0 (Also called as Webdriver)
  • Selenium GRID

Latest version of selenium is 3.4.0 which can be downloaded from https://www.seleniumhq.org/download/

Selenium supports multiple operating systems, multiple browsers and multiple languages. It gives you flexibility to choose the language in which you have expertise. Following is the list:

  • Multiple Programming Languages : Java, Python, PHP, Ruby, Perl, JavaScript
  • Multiple Operating Systems : Android, iOS, Windows, Linux, Mac, Solaris
  • Multiple Browsers : Chrome, Internet Explorer, Edge, Opera, Safari etc

Selenium Tool is known for its performance and execution speed. Let’s discuss about the different components of Selenium:

1)Selenium IDE : It is a record and play tool and a plugin of firefox. This plugin is used to create prototypes of tests. Following are the features of this tool:

  • Easy to install
  • Test Scripts are created by just click on record button
  • Can record, edit and debug scripts
  • Simplest way to learn Selenium syntax.
  • Test Scripts can be imported in multiple languages like Python with Remote Control, Java with Webdriver, Java with Remote Control, Ruby with Remote Control etc

This plugin can be downloaded from following URL:

https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/

2)Selenium 1.0 (Remote Control) : This was the first component developed in Selenium Suite. Selenium became famous because of this component. It works in following manner:

1) Using this component, we write test scripts which interacts with Selenium Remote Control Server.

2) Server interprets the code and converts it into javascript and further injected into the browsers.

3) Javascript gets executed at the browser and response is sent back to the server which forwards it to the user.

There were many drawbacks in this tool that is:

  • Confusing commands.
  • Remote Control Server acts as a mediator which makes its execution slower.
  • Use of Javascript

Selenium Webdriver (2.0/3.0) : After Selenium RC, Webdriver has come which make its architecture more simpler. Now, there is no server. Test Scripts interact directly with the browser. The execution is much faster compared to Selenium Remote Control. Selenium Commands were segregated in different classes which become easy for end user to remember and to implement.

Last year, Selenium has launched a new version that is 3.0 which is much lighter than Selenium 2.0. There are not much change done which impact the end user but multiple were done at the backend. Syntax for loading Firefox has been changed to following:

System.setProperty(“webdriver.gecko.driver”,”path to gecko driver”);

Webdriver driver = new FirefoxDriver;

Selenium Gecko Driver can be downloaded from following URL, the latest version for Gecko Driver is 0.16.1:

https://github.com/mozilla/geckodriver/releases

Selenium GRID : It is used for parallel testing. This component enable us to execute automation framework on different machines placed at different location. However, all the machines should be connected on a Local Area Network. It can be used with Selenium Remote Control as well as with Selenium Webdriver. Please note that Selenium Remote Control classes have been deprecated now. So, we couldn’t use this component with Selenium Remote Control.

Raghav

Raghav Globalservices

Blog Author

Raghav has 8+ years of experience with 7+ years of experience in Automation Testing using Selenium, Appium, Ranorex tools etc. in multiple project domains. He is a Consultant &amp; Trainer has trained more than 6000+ US, UK, Russian &amp; Indian students &amp; is a corporate Trainer for several MNCs. <a href="https://www.linkedin.com/in/aroraraghav/" rel="no follow">linkedin.com</a>

Join the Discussion

Your email address will not be published. Required fields are marked *

1 comments

hitekschools 28 Nov 2018

very useful Good job

Suggested Blogs

How to use sys.argv in Python

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use the sys module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use argv and how to pass command line arguments in Python 3.x In simple terms,Command Line arguments are a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python. These can be found in other programming languages like C, C# , C++, PHP, Java, Perl, Ruby and Shell scripting. Understanding sys.argv with examples  sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with a few examples. With the len(sys.argv) function, you can count the number of arguments. import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']Module name to be used while using sys.argv To use sys.argv, you will first need to the sys module. What is argv[0]? Remember that sys.argv[0] is the name of the script. Here – Script name is sysargv.py import sys print ("This is the name of the script: ", sys.argv[0]) print ("Number of arguments: ", len(sys.argv)) print ("The arguments are: " , str(sys.argv))Output:This is the name of the script:  sysargv.py                                                                               Number of arguments:  1                                                                                                 The arguments are:  ['sysargv.py']What is "sys. argv [1]"? How does it work? When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. So, if the below script is executed: python sample.py Hello Python Then inside sample.py, arguments are stored as: sys.argv[0] == ‘sample.py’ sys.argv[1] == ‘Hello’ sys.argv[2] == ‘Python’Here,sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script . Parsing Command Line options and arguments  Python provides a module named as getopt which helps to parse command line options and arguments. Itprovides a function – getopt, whichis used for parsing the argument sequence:sys.argv. Below is the syntax: getopt.getopt(argv, shortopts, longopts=[]) argv: argument list to be passed.shortopts: String of short options as list . Options in the arguments should be followed by a colon (:).longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). import getopt import sys   first ="" last ="" argv = sys.argv[1:] try:     options, args = getopt.getopt(argv, "f:l:",                                ["first =",                                 "last ="]) except:     print("Error Message ")   for name, value in options:     if name in ['-f', '--first']:         first = value     elif name in ['-l', '--last']:         last = value   print(first + " " + last)Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut Knowledge Hut (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut Knowledge HutWhat are command line arguments? Why do we use them? Command line arguments are parameters passed to a program/script at runtime. They provide additional information to the program so that it can execute. It allows us to provide different inputs at the runtime without changing the code. Here is a script named as argparse_ex.py: import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", required=True) args = parser.parse_args() print(f'Hi {args.name} , Welcome ')Here we need to import argparse package Then we need to instantiate the ArgumentParser object as parser. Then in the next line , we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above . This is a required argument as mentioned by required=True Output:  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan  Hi Nandan , Welcome  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan  Hi Nandan , Welcome The example above must have the --name or –n option, or else it will fail.(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name   usage: argparse_ex.py [-h] --name NAME argparse_ex.py: error: the following arguments are required: --namePassing command line arguments in Python 3.x argv represents an array having the command line arguments of thescript . Remember that here, counting starts fromzero [0], not one (1). To use it, we first need to import sys module (import sys). The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. Here, we need to slice the list to access all the actual command line arguments. import sys if __name__ == '__main__':     for idx, arg in enumerate(sys.argv):        print("Argument #{} is {}".format(idx, arg))     print ("No. of arguments passed is ", len(sys.argv))Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 Argument #0 is argv_count.py Argument #1 is Knowledge Argument #2 is Hut Argument #3 is 21 No. of arguments passed is  4Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.import secrets , sys, os , string ''' This script generates a secret password using possible key combinations''' ''' Length of the password is passed as Command line argument as sys.argv[1]''' char = string.ascii_letters+string.punctuation+string.digits length_pwd = int(sys.argv[1])   result = "" for i in range(length_pwd):     next= secrets.SystemRandom().randrange(len(char))     result = result + char[next] print("Secret Password ==" ,result,"\n")Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12 Secret Password == E!MV|,M][i*[Key takeaways Let us summarize what we've learnt so far. We have seen how to use the sys module in Python, we have looked at what areargv[0] and sys.argv[1] are and how they work, what Command Line arguments are and why we use them and how to parse Command Line options and arguments. We also dived into multiple ways to use argv and how to pass command line arguments in Python 3.xHope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out the rest of the tutorials on KnowledgeHut’s website and don't forget to practice with your code! 
Rated 4.0/5 based on 14 customer reviews
5908
How to use sys.argv in Python

The sys module is one of the common and frequently... Read More

The self variable in Python explained with Python tips

If you have been working on Python, you might have across the self variable. You can find it in method definitions and in initializing variables. However, before coming to the self variable, let us have an idea about classes and instances in Python.  What are Instance methods and Class methods in Python? You might have heard of instances and classes while working on Python. Class variables are defined within a class and they are shared with all the instances (objects) of the class whereas instance variables are owned by the instances of a class. For different instances, the instance variables are different. Likewise, Python also contains class methods and instance methods. The class methods inform about the status of the class. On the other hand, instance methods are to set or get details about instances or objects.   If you want to define an instance method, the foremost parameter of the method should always have to be self. Let us understand this with the help of example code – class myClass:      def instance_method(self):          return “Instance method is called”, self The method “instance_method” is a regular instance method. The method accepts one single parameter – self. The self variable points to an instance of the class myClass when the method is revoked. Though the method takes only one parameter here, it can also accept more than one parameter. The instance methods can easily access different attributes and other methods on the same object with the help of the self variable. The self variable also has the power to modify the state of an object and using the self.__class__  attribute, instance methods can also access the class. Thus, the instance methods are also able to modify the class state. Now, let us see what happens when we call “instance_method”: >>>obj = myClass()  >>>obj.instance_method()  ('Instance method is called', ) This shows that “instance_method” can access the object instance (printed as ) through the self parameter. What happens is that the self parameter is replaced with the instance object obj when the method is called. However, if you pass the instance object manually, you will get the same result as before: >>>myClass.instance_method(obj)  ('Instance method is called', ) Note that self is actually not a defined keyword in Python but a convention.What is Self in Python? Unlike this variable in C++, self is not a keyword rather it is more of a coding convention. It represents the instance or objects of a class and binds the attributes of a class with specific arguments. The use of self variable in Python helps to differentiate between the instance attributes (and methods) and local variables. If you do not want the variables of your class to be shared by all instances of the class, you can declare variables within your class without self. Let us understand this with an example: class Car:      def __init__(self, model):  self.model = model      def Car_info(self):  print("Model : ", self.model) Here, we have declared a class Car with one instance variable self.model = model. The value of the instance variable will be unique to the instance objects of the class that might be declared. However, if you want the variables to be shared by all instances of the class, you need to declare the instance variables without self. Otherwise, it would be ambiguous since all cars will have the same model. Need for Self in Python The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.  Unlike other programming languages, Python does not use the “@” syntax to access the instance attributes. This is the sole reason why you need to use the self variable in Python. The language contains methods that allow the instance to be passed automatically but not received automatically. Explicit definition of self The Zen of Python says “Explicit is better than Implicit”. Programmers of other languages often ask why self is passed as an explicit parameter every time to define a method. There are a few reasons for this. Firstly, since Python uses a method or instance attribute instead of a local variable when we read self.name or self.age, it makes it absolutely clear you are using an instance variable or method even if you have no knowledge about the class definition. Secondly, if you explicitly refer or call a method from a particular class in Python, you do not need to use any special syntax for that.  Finally, the third reason is that the explicit definition of self helps Python understand whether to assign to an instance variable or to a local variable. In simpler terms, local variables and instances exist in two separate namespaces and we need to inform Python which namespace should be used. What is a Python class self constructor? The self variable in Python can also be used to access a variable field within the class definition. Let us understand this with the help of example code: class Student:     def __init__(self, Alex):          self.name = Alex    #name created in constructor      def get_student_name(self):          return self.name In the example above, self refers to the variable age of the class Student. The variable age is local to the method. While the method is running, the variable age exists within the class. If there is a variable within a method, the self variable will not work. If you wish to define global fields, you need to define variables outside the class methods.   Is self a keyword in Python? There is a question that always hovers among Python programmers. Is self actually a keyword in Python? Unlike other programming languages like C++, where self is considered to be a keyword, in Python it is a convention that programmers tend to follow. It is basically a parameter in a method definition. However, you can use any other name in place of self like another or me or anything else for the first parameter of a method. Another reason why it is suggested by most people is that it enhances the readability of your code. Let us see an example to understand it: class myClass:   def show(another):   print(“another is used in place of self”)  If you compare this code with the code for the Python class self constructor, you will notice that here we have used the name another in place of self. Now let us create an object of this class and see the output: object = myClass()   object.show()another is used in place of selfYou can see that the program works even if we use some other name in place of the self variable. It works exactly the same way as the self variable does. Why "self" should be used as the first parameter of instance methods in python  This can be understood by the below example. We have a Rectangle class which defines a method area to calculate the area : class Rectangle ():      def __init__(self,x = 0,y = 0):          self.x = x          self.y = y      def area (self):          """Find area of rectangle"""          return (self.x * self.y)  rec1=Rectangle(6,10)  print ("Area is:", rec1.area()) Output:  Area is: 60    In the above example, __init__() defines three parameters but only 2 arguments are passed (6 and 10). Similarly, area () requires one but no arguments are passed.  Rectangle.area and rec1.area in the above example are different and not exactly the same. >>> type(Rectangle.area )    >>> type(rec1.area)  Here, the first one is a function and the second one is a method. A unique feature of Python is that the object itself is passed as the first argument to the corresponding function. In the above example, the method call:  rec1.area()is equivalent to:  Rectangle.area(rec1). Generally, when the method is called with some arguments, the corresponding class function is called by placing the method's object before the first argument.  Therefore: obj.method(args) becomes Class.method(obj, args). This is the reason the first parameter of a function in a class must be the object itself. Writing this parameter as self is merely a convention and not a keyword so it has no special meaning in Python. We could use other names (like this, that) but it is not preferred as it degrades code readability.Should we pass self to a method? Since we can use any other name instead of using the self variable, then what will happen if we just pass self to a method definition. Let us consider the class myClass we have used earlier.  A method named something is defined within the class with a parameter another and two arguments: class myClass:   def something(another, argument1, argument2):   pass Now, let us declare an instance obj of myClass and call the method something with the help of the instance object: obj = myClass()  obj.something(argument1, argument2) Python performs an internal work on the method call and converts it into something like this: myClass.something(obj, argument1, argument2)  This shows that another variable (used in place of self) refers to the instance object of the class. Note that the pass keyword used in the method something does nothing. It is used as a dummy in situations where you do not want any operation to be performed but there is a syntax requirement of a certain programming element. How can we skip self in Python? Consider a situation where the instance method does not need to have access to the instance variables. In such cases, we can consider skipping the self variable in defining methods. Let us have a clear understanding of the fact with example code: class Vehicle:  def Car():  print(“Rolls Royce 1948”)  obj = Vehicle()  print(“Complete”) If you run the following code, the output will be as follows: Complete We have not declared the self variable here but there is still no error in the program and the output comes out fine. However, what will be the case if we call the Car() method: obj = Vehicle()  obj.Car() When we compile the code after calling the Car() method, it shows an error like this: Traceback (most recent call last):   File "", line 11, in   TypeError: Car() takes 0 positional arguments but 1 was given The output shows an error since the method Car() takes 0 positional arguments but we have given 1 positional argument to it. This is because when the instance obj is created, it is automatically passed as the first argument to the method Car() even if we have not declared the self variable. However, if you try to access the instance method Car() with the help of the class reference, there will be no errors and the program will work fine: class Vehicle:  def Car():  print("Rolls Royce 1948")  obj = Vehicle()  Vehicle.Car()  Rolls Royce 1948 Difference between self and __init__  self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed. __init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and allows the class to initialize class attributes .. Usage of "self" in class to access the methods and attributes: class Rectangle:     def __init__(self, length, breadth, cost_per_unit =0):         self.length = length         self.breadth = breadth         self.cost_per_unit = cost_per_unit     def perimeter(self):         return 2 * (self.length + self.breadth)     def area(self):         return self.length * self.breadth     def calculate_cost(self):         area = self.area()         return area * self.cost_per_unit  # length = 40 cm, breadth = 30 cm and 1 cm^2 = Rs 100  r = Rectangle(40, 30, 100)  print("Area of Rectangle:",r.area())  print("Cost of rectangular field is : Rs ",r.calculate_cost()) Output:  Area of Rectangle: 1200  Cost of rectangular field is : Rs  120000 We have created an object of Rectangle class. While creating the Rectangle object, we passed 3 arguments – 40,30,100; all these arguments are passed to "__init__"method to initialize the object. Here, the keyword "self” represents the instance of the class. It binds the attributes with the given arguments. Self represents the same object or instance of the class. If you see, inside the method "area” , self.length" is used to get the value of the attribute "length".  attribute "length" is bind to the object (instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement “r = Rectangle(40,30, 100)".  If you see the method definition "def area(self): ” , here "self" is used as a parameter in the method because whenever we call the method,  the object (instance of class) is automatically passed as a first argument along with other arguments of the method. If no other arguments are provided only "self" is passed to the method. That's the reason "self" is used to call the method inside the class("self.area()").  We used object (instance of class) to call the method outside of the class definition("r.area()").  "r" is the instance of the class when the method "r.area()” is called; the instance "r" is passed as first argument in the place of self. Miscellaneous Implementations of self Let us now discuss some of the miscellaneous implementations of the self variable. Similar variables for Class Method and Static Method A class method is a method that is bound to the class. Let us understand a class method with an example – class myClass:  @classmethod  def classmethod(cls):  return “Class Method is called”  obj.classmethod() The same behavior of the self variable is present with the Class methods too but the only difference is that for class methods, the convention is to use cls as the variable name instead of self. The class methods take a cls parameter instead of the self parameter. When the method is called, it points to the class. The class method cannot modify the object state but it can modify the class state of all the class instances. On the other hand, static methods are self-sufficient functions and this type of method takes neither a self nor a cls parameter. Let us see an example of a static method – class myClass:  @staticmethod  def staticmethod():  return “Static Method is called”  obj.staticmethod() Since a static method does not accept any parameter, they cannot modify object state or even class state. They are primarily used to namespace different methods and Python restricts them in the data they can access. Note that both the methods here are marked with @classmethod and @staticmethod decorators to flag it as a class method and static method respectively. The self variable is bound to the current instance The self variable allows us to access the properties of the current instance. Let us understand this with an example – class Person:  def __init__(self, n):  self.name = n  def walk(self):  print(f“{self.name} is walking”)  obj1 = Person(“Alex”)  obj2 = Person(“Charles”)  obj1.walk()  obj2.walk()  Alex is walking Charles is walking Here, we have a class Person with two methods __init__ and walk declared with the self parameter. We have created two different instances of the class – obj1 and obj2. When the first instance is revoked, “Alex” is printed with the method walk() whereas when the second instance is revoked, “Charles” gets printed with the properties of the instance method walk(). Tips about the Python self variable Since we have now reached the end of the article, let me give you some tips about when to use and when not to use the self variable in Python. Use self when:you define an instance method, since it is passed automatically as the first parameter when the method is called;you reference a class or an instance attribute from inside an instance method;you want to refer to instance variables and methods from other instance methods. Don’t use self when: you want to call an instance method normally;referencing a class attribute inside the class definition but outside an instance method;you are inside a static method.  Conclusion Let us recap the key points we have covered in this article, namely:Instances and Classes in Python. Self variable and its importance. The explicitness of the self variable. Python class self constructor. Passing self as a method. Skipping self in Python. Variables used for Class methods and Static methods. Bounding of self to the current instance. When to use and when not to use self in Python. With good knowledge about the self variable in Python and its internal working in Python, it is now time for some practice. If you, however, wish to know more about Python self, you can head right on to the official documentation of Python.Happy coding! 
Rated 4.0/5 based on 10 customer reviews
12369
The self variable in Python explained with Python ...

If you have been working on Python, you might have... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
Rated 4.5/5 based on 9 customer reviews
3598
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

Useful links