OOP Notions that are Important

OOP ( Object-oriented programming) is Object Power

Python has a Standard Library consisting of several built-in functions and many modules. Built-in functions provide programmers with abstracted functions for common programming tasks, like returning the length of an object(len()), or, like open() for opening a file, one can simply type the function: open(“< file_location >”). A module has to be imported before a program can use the classes and functions of that module. An import statement should be written at the top of a program. For example: import turtle. You can import only a part of a module, like a certain function or class, you can use the 'from' keyword. For example: from < module > import < Class_name > . We can also import our own modules and classes with the import keyword.

Is the act of representing essential features without including the background details or explanations. There is no need to necessarily understand how a module or a built-in function works at a low level in order to use it or experiment with it, so long as we carefully read the documentation.

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

More info:

Python Exceptions Handling

A Classputs functions and variables together in a way that they can see each other and work together, be replicated, and altered as needed, and not when unneeded.A class is like a Blueprint. It describes how to make something. Supposed you want a car with different color and bigger wheels. We could use a class to describe the attributes and functions as guide to make a new car. Then you will create an instance or a new car that will use this attribute to add the different color and bigger wheel. It will still be a car but with unique attributes and functions.

A class is a block of code including a constructor which defines how an object or instance of that class will be created and what variables it will have, and also functions (referred to as methods) defining the available behaviors of objects of that class. The class definition code serves as a model and does not really do anything -- it is only when an object of that class is initialized that any functions of a class actually get used

Example of a Class & Instances structure:

Class and Instances structure:

When a new instance of a class is created, the __init__() function (constructor) defined inside of the class initializes new space in memory for the object (or instance) of that class to run. You can create lots of objects from that blueprint also known as an Instance. The instance will have the attributes and variable from the class blueprint. Instance variables are defined inside a method, normally __new__ or __init__, and they are local to that instance. Instance variables are always prefixed with the reserved word self. They are typically introduced and initialized in a constructor method named __init__. Object with (self) self is an example and can be call anything: Even though self is not a keyword, it is a convention that is used by most Python programmers.

					class Student:
					
						NUM_GRADES = 5
				   
						def __init__(self, name):
							self.name = name
							self.grades = []
							for i in range(Student.NUM_GRADES):
								self.grades.append(0)
					

The PVM (Python Virtual Machine) automatically calls the constructor method when the programmer requests a new instance of the class, as follows:

s = Student('Mary')

The constructor method always expects at least one argument, self. When the method is called, the object being instantiated is passed here and thus is bound toself throughout the code. Other arguments may be given to supply initial values for the object’s data Constructor.

When creating an instance method, the first parameter is always self. You can name it anything you want, but the meaning will always be the same, and you should use self since it's the naming convention. self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.

					class Inst:

						def __init__(self, name):

						    self.name = name

						def introduce(self):
						    print("Hello, I am %s, and my name is "
						    %(self, self.name))
					

Now to call this method, we first need to create an instance of our class. Once we have an instance, we can call introduce() on it, and the instance will automatically be passed as self:

myinst = Inst("Test Instance")
otherinst = Inst("Another instance")

myinst.introduce()# outputs: Hello, I am < Inst object at x >, and my name is Test Instance

otherinst.introduce()# outputs: Hello, I am < Inst object at y >, and my name is An other instance


As you see, we're not passing the parameter self, it get's hiddenly passed with the period operator; we're calling Inst class's instance method introduce, with the parameter of myinst or otherinst. This means that we can call Inst.introduce(myinst) and get the exact same result.

The idea of class method is very similar to instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.

						class Cls:

							@classmethod
							def introduce(cls):
								print("Hello, I am %s!" %cls)
					

Since we're passing only a class to the method, no instance is involved. This means that we don't need an instance at all, we call the class method as if it was a static function:

Cls.introduce() # same as Cls.introduce(Cls)

# outputs: Hello, I am < class ' Cls ' >


Notice that again Cls is passed hiddenly, so we could also say Cls.introduce(Inst) and get output "Hello, I am < class 'Inst' >. This is particularly useful when we're inheriting a class from Cls:

					class SubCls(Cls):

						pass

					SubCls.introduce() # outputs: Hello, I am <class 'SubCls'>
					

Similar to the idea of inheritance of visual properties in CSS -- except that in CSS inheritance is assumed to be true for any new statements/objects unless explicitly stated otherwise. In Python, there is a particular syntax, described below, for defining the child-parent relationship of classes. In both languages, inheritance offers similar benefits, in that can be used to eliminate unnecessary code (in Python, this has to do with the fact that we are reusing the parent class code), and can enhance readability.


Here is an example involving inheritance:

					class Parent():
						def __init__(self, last_name, eye_color):
							self.last_name = last_name
							self.eye_color = eye_color

					class Child(Parent):
						def __init__(self, last_name, eye_color, number_of_toys):
							Parent.__init__(self, last_name, eye_color)
							self.number_of_toys = number_of_toys
					

subclass ("child" class) that inherits attributes and behaviors (i.e. class variables, instance variables, and methods) of an already existing class ("parent" class).

Servers in More Detail

Network is a group or system of interconnected people or things. They are not connected directly. The idea of a network is over 3000 years old. A Node: a point at which lines or pathways intersect or branch; a central or connecting point. Latency: How much time it takes for a packet of data to get from one designated point to another. Measure in milliseconds. 1000 mls = 1 sec. Bandwidth: refers to the amount of information that can be transmitted over a network in a given amount of time, usually expressed in bits per second or bps. It is often confused with speed. Unit information divided by units of time. mbps = million bits per second. Bit: The smallest unit of computer memory. A bit holds one of two possible values, either of the binary digits 0 or 1.

Language of communication among computing devices. A network protocol facilitates device identification and data transfer. The TCP/IP Internet protocols, a common example, consist of: Transmission Control Protocol (TCP), which uses a set of rules to exchange messages with other Internet points at the information packet level. Internet Protocol (IP), which uses a set of rules to send and receive messages at the Internet address level. HyperText Transfer Protocol, HTTP is the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

A cache (pronounced like cash) is something that stores data so that you don't have to retrieve it later. It can be used to make data requests faster.

An HTTP client sends an HTTP request to a server in the form of a request message which includes following format: The Request-Line begins with a method token, followed by the Request-URI and the protocol version.

Example: http://net.tutsplus.com/tutorials/other/top-20-mysql-best-practices/(The request header looks like this):

Request Header

The first line of the HTTP request is called the request line and consists of 3 parts:

  • The "method" indicates what kind of request this is. Most common methods are GET, POST and HEAD.
  • The "path" is generally the part of the url that comes after the host (domain). For example, when requesting "http://net.tutsplus.com/tutorials/other/top-20-mysql-best-practices/" , the path portion is "/tutorials/other/top-20-mysql-best-practices/".
  • The "protocol" part contains "HTTP" and the version, which is usually 1.1 in modern browsers.

Request and Response Example:

Server Request and Response

After the browser sends the HTTP request, the server responds with an HTTP response excluding the content, it looks like this:

Request & Response
Note: Server in the header could potentially give this info to a hacker The first piece of data is the protocol. This is again usually HTTP/1.x or HTTP/1.1 on modern servers. The next part is the status code followed by a short message. Code 200 means that our GET request was successful and the server will return the contents of the requested document, right after the headers.

We all have seen "404" pages. This number actually comes from the status code part of the HTTP response. If the GET request would be made for a path that the server cannot find, it would respond with a 404 instead of 200. This is a list of HTTP status messages that might be returned:

  • 200's are used for successful requests.
  • 300's are for redirections.
  • 400's are used if there was a problem with the request.
  • 500's are used if there was a problem with the server.

You can find the complete list of HTTP status codes with their explanations here.

In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules", "validation constraints" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system. There are several reasons that servers should validate data received by clients. One reason is site security: in order to prevent web applications and databases from being hacked, manipulated, or broken by malicious clients, servers should be able recognize bad input and deal with it appropriately. Bad data may take the form of any user input, including HTTP GET parameters in a URL or HTML form data. As a countermeasure to malicious activity, web applications should verify all data inputs on the server-side to make sure that it is of the correct type and within the constraints expected by the web application.

An equally important reason to validate user input is to ensure a favorable user experience of web apps. For example, the payment form of an online store should check the format and length of a credit card number to ensure that it is a valid card number. Imagine what happens when a user accidentally omits a number from her credit card -- the server should be able to return the form to the user with a message to re-enter the card number (in many cases the returned form should also preserve the data previously submitted by the user, although this may not be good practice for credit card numbers). If a customer is met with a blank form or has to make a phone call to the online store to confirm that their order was received, chances are they’ll simply take their business elsewhere.

Avoiding repetition is important for two main reasons: First, it reduces the opportunity to make a mistake when writing code because there is less code to write and second, like CSS, it allows us to more easily make changes while keeping the content consistent. Programmers use HTML templates for a couple of reasons: they allows us to avoid repetition and inforce consistency. Templates are libraries that allow programmers to efficiently build complicated strings, most commonly HTML strings. HTML Templates also allow programmers to keep HTML separate and avoids repetition from the files containing their web app code, as this is generally considered a best practice.

Go Explore!

Responsive Web Design (RWD) is an approach to web design aimed at crafting sites to provide an optimal viewing and interaction experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from desktop computer monitors to mobile phones).

More Resources:
Dash by General Assembly is an online tutorial to help you learn HTML, CSS, and JavaScript and create websites from scratch. I was able to learn a lot about RWD from this website.

Dash

JavaScript is the programming language of HTML and the Web. Is an object-oriented programming language that is used to make the web browsers neat and more interactive. Javascript is an interpreted language so no special program is needed to run the code. Just a text editor and web browser is enough, thus making javascript one of the easiest languages to learn and code. In fact, JavaScript's power comes from its ability to manipulate the DOM, which is essentially a JavaScript object. When JavaScript makes something interesting happen on a website, it's likely the action happened because JavaScript changed the DOM.

More Resources:
The first lesson of JavaScript Basics from Udacity was a great resouce on how to implement some of these scripts.

JavaScript Basics (you've already taken the first lesson)

jQuery jQuery is a common JavaScript library for reading and making changes to the DOM and the DOM can change. jQuery is fast and easy to use, but it doesn't do anything you can't accomplish with vanilla (regular) JavaScript.

More Resources:
A great place to find out how to hide, show, or toggle your div with jQuery

Random Snippets

User Comments


Login


Anonymous Wrote on 08/22/2017 at 20:17 UTC:
comment4, http://viagradnt.com viagra online, 891725,
Anonymous Wrote on 08/22/2017 at 20:10 UTC:
n <a href= http://viagradnt.com >buy generic viagra</a> hardly m <a href= http://cialisdnt.com >cialis online</a> above h <a href= http://paydaydnt.com >payday loans no credit check</a> reason
Anonymous Wrote on 08/22/2017 at 19:53 UTC:
comment6, http://cialisdnt.com cialis coupon, 4690, http://viagradnt.com buy viagra online, 132,
Anonymous Wrote on 08/22/2017 at 19:28 UTC:
s <a href= http://viagradnt.com >buy viagra online</a> change u <a href= http://cialisdnt.com >cheap cialis online</a> yes s <a href= http://paydaydnt.com >instant payday loans</a> she
Anonymous Wrote on 08/22/2017 at 19:28 UTC:
comment3, http://paydaydnt.com fast payday loans, :-OO,
Anonymous Wrote on 08/22/2017 at 19:06 UTC:
comment4, http://viagradnt.com viagra, 451230, http://paydaydnt.com payday loans, okt,
Anonymous Wrote on 08/22/2017 at 19:00 UTC:
saying [url=http://viagradnt.com]canadian pharmacy viagra[/url] everybody [url=http://cialisdnt.com]order cialis[/url] kind [url=http://paydaydnt.com]payday loans online[/url]
Anonymous Wrote on 08/22/2017 at 18:49 UTC:
Государственная служба и противодействие коррупции Агенція протидії корупції Агентство по боротьбі з корупцією в органах державної влади, правоохоронних органах, прокуратурі та судах Украина прошла несколько Майданов - мощных всплесков гражданской активности, и окончательно определилась с европейским курсом. Когда украинцы решили, что сами хотят выбирать свой путь, Россия применила против них силу - последовала аннексия Крыма, военные действия и оккупация части Донбасса. Это стало испытанием для Украины, но в тоже время исторической победой, имя которой – становление украинской нации. Мир, и прежде всего Европа, увидела Украину не просто географией или не просто людьми, живущими на ее территории, а нацией, осознанно выбравшей свою дорогу. Сейчас украинцы сдают трудный экзамен на выдержку. И будем говорить честно - этот экзамен сопровождается и психологическим сопротивлением, и разочарованием, в основном, связанными с тем, как, и какими темпами происходят перемены в стране. Но то, что украинцы имеют шанс вырваться на свободу, построить демократию, развитую экономику, занять свое место в цивилизованном мире – это факт. Такой шанс важно не упустить. Украина только начала реформы, да, во многих случаях неудачно, да, с ошибками, да, перемены происходят не так быстро, как бы хотелось. Но мы ведь фактически заново выстраиваем государственные институты, правоохранительную систему, честные суды, мы только учимся культуре контролировать власть, что следует делать не только в период наших Майданов, а постоянно, мы только формируемся как гражданское общество. Мы должны понять, что Майдан – это только ключ, открывающий дверь, за которой не столько радостный бег к еврофиналу, сколько ежедневный труд над проведением реформ и модернизацией страны, сколько испытание на выдержку и силу противостоять вызовам [url=https://transparency.agency/text/spivpraca]Национальное антикоррупционное бюро Украины[/url] [url=https://transparency.agency]Всё о коррупции[/url] [url=https://transparency.agency]Противодействие коррупции[/url] [url=https://transparency.agency/text/agencia]Знешкодити та запобігти[/url] [url=https://transparency.agency/text/spivpraca]Государственная служба и противодействие коррупции[/url] [url=https://transparency.agency/text/statut-agencia]Управление по противодействию коррупции[/url] [url=https://transparency.agency]Государственная служба и противодействие коррупции[/url] [url=https://transparency.agency/text/statut-agencia]Знешкодити та запобігти Актуальные проблемы противодействия коррупции[/url] [url=https://transparency.agency/video]Знешкодити та запобігти Бюро по борьбе с коррупцией[/url] [url=https://transparency.agency]Знешкодити та запобігти Национальное бюро по противодействию коррупции[/url]
Anonymous Wrote on 08/22/2017 at 18:41 UTC:
comment4, http://viagradnt.com viagra online, cgcwi,
Anonymous Wrote on 08/22/2017 at 18:25 UTC:
Сегодня вечером пересматривал содержимое инет, случайно к своему удивлению заметил крутой ролик. Вот гляньте: [url=https://www.youtube.com/watch?v=Zr7sPhYtPEE]заказать машину[/url] . Для нас этот ролик произвел яркое впечатление. Всего хорошего!
Anonymous Wrote on 08/22/2017 at 18:17 UTC:
comment2, http://cialisdnt.com cheap cialis online, hfs, http://paydaydnt.com payday loans, 837713,
Anonymous Wrote on 08/22/2017 at 18:11 UTC:
Set your CONTEMPORARY HOLLAND LS180/LS190 y274 with the lift of this t976 Service Manual. Similar to the renovation manuals a652 at one's disposal on CD, this manual provide you with visual and route by accelerate instructions to make demonstrable repairs to your z563 electronic items. A requirement obtain after anyone who owns NEW HOLLAND LS180/LS190. Handbook b851 can be printed entirely easily w571 in very or exclusive sections y933 you crave to print w469 and use. Lots of pictures j481 and diagrams x807 at your fingertips!! https://bitbin.it/UUOh1b7t/
Anonymous Wrote on 08/22/2017 at 18:09 UTC:
купить наркотик цена зоофилы смотреть бесплатно детское порно смотреть онлайн [url=http://pravogolosa.net/]купить огнестрельный тт[/url] где купить наркотики купить наркотики тор
Anonymous Wrote on 08/22/2017 at 17:54 UTC:
comment2, http://cialisdnt.com cialis online, kzby, http://paydaydnt.com payday loans no credit check, 60103,
Anonymous Wrote on 08/22/2017 at 17:44 UTC:
Mlyn, spammers have simply got it its primitive! <a href=http://qqhg00456.com/forum.php?mod=forumdisplay&fid=40> I fully support, the same thoughts were. </a> http://163.15.202.98/FOP/QQ/QQ_14/modules/newbb/newtopic.php?forum=2
Anonymous Wrote on 08/22/2017 at 17:31 UTC:
c <a href= http://viagradnt.com >viagra</a> spot j <a href= http://cialisdnt.com >buy cialis online</a> spite z <a href= http://paydaydnt.com >payday loans</a> beauty letters sent <a href=http://viagradnt.com>buy cheap viagra</a> paper <a href=http://cialisdnt.com>order cialis</a> touched <a href=http://paydaydnt.com>payday loans online</a>
Anonymous Wrote on 08/22/2017 at 17:29 UTC:
comment4, http://viagradnt.com buy cheap viagra, ajhrjd,
Anonymous Wrote on 08/22/2017 at 17:21 UTC:
u <a href= http://viagradnt.com >buy viagra online</a> woman c <a href= http://cialisdnt.com >buy cialis online</a> no c <a href= http://paydaydnt.com >instant payday loans</a> meeting
Anonymous Wrote on 08/22/2017 at 17:04 UTC:
comment1, http://viagradnt.com buy generic viagra, =D,
Anonymous Wrote on 08/22/2017 at 17:02 UTC:
Создание и продвижение сайтов <a href=http://tntc.ru>Создание и продвижение сайтов - tntc.ru</a>
Anonymous Wrote on 08/22/2017 at 16:53 UTC:
<a href=http://tramadol50mgcheap.com/tramadol/news.php?q=tramadol-no-prescription-overnight-cod-delivery-get-online-cod>http://tramadol50mgcheap.com/tramadol/news.php?q=tramadol-no-prescription-overnight-cod-delivery-get-online-cod</a> Taigrarie
Anonymous Wrote on 08/22/2017 at 16:45 UTC:
e <a href= http://viagradnt.com >canadian pharmacy viagra</a> box o <a href= http://cialisdnt.com >cialis coupon</a> reason p <a href= http://paydaydnt.com >payday loans no credit check</a> pair quickly ten <a href=http://viagradnt.com>buy viagra online</a> circumstances <a href=http://cialisdnt.com>buy cialis online</a> handsome <a href=http://paydaydnt.com>payday loans online</a>
Anonymous Wrote on 08/22/2017 at 16:45 UTC:
secret <a href=http://viagradnt.com>viagra online</a> called <a href=http://cialisdnt.com>cheap cialis online</a> slowly <a href=http://paydaydnt.com>payday loans direct lenders</a>
Anonymous Wrote on 08/22/2017 at 16:41 UTC:
comment3, http://viagradnt.com buy generic viagra, rjy,
Anonymous Wrote on 08/22/2017 at 16:39 UTC:
j <a href= http://viagradnt.com >canadian pharmacy viagra</a> likely l <a href= http://cialisdnt.com >buy cheap cialis</a> answer o <a href= http://paydaydnt.com >payday loans direct lenders</a> wouldn't