python class
Python hosting: Host, run, and code Python in the cloud!
Introduction
Technology always evolves. What are classes and where do they come from?
1. Statements:
In the very early days of computing, programmers wrote only commands.
2. Functions:
Reusable group of statements, helped to structure that code and it improved readability.
3. Classes:
Classes are used to create objects which have functions and variables. Strings are examples of objects: A string book has the functions book.replace() and book.lowercase(). This style is often called object oriented programming.
Lets take a dive!
Python Courses:
Python Programming Bootcamp: Go from zero to hero
Python class
We can create virtual objects in Python. A virtual object can contain variables and methods. A program may have many different types and are created from a class. Example:
class User: |
Run this program. In this code we have 3 virtual objects: james, david and eric. Each object is instance of the User class.

In this class we defined the sayHello() method, which is why we can call it for each of the objects. The init() method is called the constructor and is always called when creating an object. The variables owned by the class is in this case “name”. These variables are sometimes called class attributes.
We can create methods in classes which update the internal variables of the object. This may sound vague but I will demonstrate with an example.
Class variables
We define a class CoffeeMachine of which the virtual objects hold the amount of beans and amount of water. Both are defined as a number (integer). We may then define methods that add or remove beans.
def addBean(self): |
We do the same for the variable water. As shown below:
class CoffeeMachine: |
Run this program. The top of the code defines the class as we described. The code below is where we create virtual objects. In this example we have exactly one object called “pythonBean”. We then call methods which change the internal variables, this is possible because we defined those methods inside the class. Output:
|
If you are new to Python programming, I highly recommend this book.
Leave a Reply:
if when we define a class , self is always there?
self is a reference to the variables in the functions. That is to say, self can be used anywhere inside the class but not outside it. What you are instructing the computer is "I want to access variables from this class.". This is always from within a method inside the class. You should see 'self' as the assignment of the variables in logic, not as ownership for all bojects.
I think an example will be more clear, it's in pseudo code:
If you create an object (user) randy and call randy.doSomething(3), the variable is not stored anywhere. If you call randy.somethingElse(3), randy.y will contain y because of the assignment with self.y
Every object created from a class has it's own variable assignments. You could have a User and create 3 users from the class. Each of the user objects can have its own name, email, age.
Would it be possible to add the solutions to the exercises as a spoiler format/pop up so that one can check their code?
Hi! These are the answers to the questions, I tried them on Python 2.7.6. If anything doesn't run or want more explanation, let me know. Here you go:
*** spoiler, answer to exercises ***
Part 1: Classes in Python
1 and 2:
3:
5.
Part 2: Changing internal variables
1, 2:
3.
hello i tried this but it didn't run can you help me?
sorry for my bad english.
thanks
Hi, are you getting any error? Which exercise did you try?
I tested them with Python 2.7.6. If you are using Python 3 put brackets around the print command, such that print("command").
Do you happen to speak Dutch (Nederlands) by any chance? (translated below)
Yes, I speak dutch.
Which error do you get?
I get this error:
Traceback (most recent call last) :
What is written below Traceback? Which program?
I created a screenshot:
https://pythonspot.com/wp-content/uploads/2015/06/screenshot.jpg
You are in the Python shell, copy the code to a file named test.py and execute using: execfile('test.py').
Alternative:
What should happen? A command line screen appears but is gone within a second.
Press windows key + R (start, run), type command or cmd. A command line screen will appear, then:
The file does test.exe does not exist. From the command line run python.exe with the parameter to the path test.py.
Of course the path must be correct. You could use a GUI like PyCharm if you prefer.
Hey Frank I'm new in python i just want to understand what does " " means when u write name = " " what does it store? thank you
Hi, when a new object is created using a class, this object will have the string variable name. This string value will have an empty string.
In this case, the virtual objects james, david and eric have a variable name. We set this name in the constructor __init__(self, name).
Hey frank, could you please elaborate on what a constructor does and why is it used?
Hi, the constructor function is only called when creating a new object. This function can initialize the variables of that particular object. In the case of class User, the constructor is used to set the name variable. We call the constructor with:
And the constructor sets the variable name:
Constructors are typically only used to initialize variables of objects.
Change the order and amount of sayHello() calls
please let me no about this Exercises, I am not getting
Hi, this simply means to change the number of calls to sayHello() and the order. For example:
Hi! Could you maybe answer this same question in Dutch?
Het 'self' keyword bestaat alleen binnen de klasse. Het gebruik van 'self' beperkt zich tot binnen de methoden. Het doel van self is het toekennen van waarden en aanroepen van methoden binnen de eigen klasse.
I'm migrating from Java, so I'm just wondering - why there is a basic difference between function declaration and a class method with using a 'function' keyword. In class method you are not allowed to use this keyword while for simple function declaration - it work in both cases - with and without using keyword ?
Hi Vitaliy, do you mean the self parameter?
The self parameter needs to be specified for classes by design, which is not necessary in Java.
Explicitly defining the self parameter is needed for these reasons:
<ul>
<li>Local variables are all variables in the function body (by definition). Self is the only method to access class variables. From a Java perspective, it is similar to some coding standards that require m_ or m to be added before the variable name, where 'm' implies member of the class. The difference being that in Python its not optional. </li>
<li>If you want to call the method from a particular class, no special syntax is necessary. </li>
<li>Reading self.x or self.task() makes it absolutely clear that an instance variable or method is used.</li>
</ul>
this giving error
SyntaxError: invalid syntax
second ex :
SyntaxError: invalid syntax
Hi James,
Save all of the code to a file called program.py then start the interpreter with a Python file: python program.py
Hi, the Class method's 1st parameter must be self ?
Yes, this is a requirement in Pythons implemention of object orientation. Every method in a class needs to have self, but for methods outside the class that is not necessary.
Hey Frank, what is the purpose of the class variables, i see you don't use them at all. Are those class attributes of that particular instance? Thanks mate
Hi Radu,
When you create 'virtual objects', the new objects created have these variables. Yes, they are variables accesible for new instances.
For example: If we create a class Mail, every Mail object can have several variables like sender, to, title, message, date.
Thanks for the example, so these are instance variables(self.sender, self.title etc.)that are unique per object(workmail and friendmail) in this case right? But i was referring to class variables from your main example above, those before the __init__ constructor (eg. name = '', beans = 0, water = 0). Why did you used them? Was that necessary? Sorry for this maybe, dumb questions. I'm in my early stages of programming and you know how it is.. Thanks again!
Hi Radu,
Right
These are similar to those defined inside the __init__, they are variables unique per instance. Every Coffeemachine instance has these variables. In some other languages (Java, C#, C++) they need to be on the top, but in Python it's fine if you define them in __init__ only. Thus, in Python you can choose which you prefer
Okey, thanks. Then i will initialize/use them in __init__ only if you say so, i guess it is more readable from my point of view, which belongs to which and so on.
Hi Frank,
in above example, the Class variables ( Bean, name, water), are they global variables? how and where do we define/declare Global Variables?
Thanks
Hi Saqib Ali khan,
They are class variables. Every new object will have these variables. These variables belong to objects and are not global variables. A global variable should be defined on top of the code, and use 'global' inside a function to access it
self is not key word ,right ? I use it replace self and it's going well
Hi, this works in both python 2.5 and 3. The first argument is often called self, which is nothing more than a convention. By not following the convention your code may be less readable to other Python programmers. The reason you need self (or the name you pick), is because Python uses it to refer to object attributes.
Hi Than,
If you use Python 3 use brackets around the print statement. Make sure you use four spaces, Python is very strict about that.
Try the code below:
Good luck!
Wow...you offer all these awesome tutorials in English...and then you also provide translation to Dutch when needed. You are the MAN. I'm not a Dutch-speaker, but that is still so awesome. I just wanted to say thank you for all of your efforts. I'm really knocking this down (I come from a C#/Java background) thanks to your clear, concise, and thorough instruction!
What is the purpose of the special functions inside a class construct?
The functions in a class can be called when an object is created. Take for example, the object james. The function james.sayHello() can be called, but is defined in a class.
Hi Frank,
i am begginer in python. kindly if you could let me know in this code what is meaning of this line [desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)].
what is % and .2f? what this line is doing?
Hi Sadia, %.2f will format the variable as a number with two digits in the end. Take for illustration:
Which will output 2.16. The 'f' in %.2f tells Python to use a floating point number (a number with digits after the comma)
Dear Frank,
Please if you could elaborate the lines of your program as i have done work in java so i am bit confused. i have written my questions with code lines. Please also let me know is it compulsory to make init as you said it is constructor. like in java one can make constructor if it needs but it is not compulsory.
In OOPS programming languages like C++ and Java, We have Access levels like Public, Private and Protected type within classes. Do Python supports these access levels in classes. If yes, can you give me an example referring all these 3 within same class
You can emulate private variables using the __ prefix. Variables like __foo are not visible outside the class, but you can access them if you workaround. There is no protected in Python. By default all variables are public
Making a constructor is optional in Python. Name is a class variable. Pythons self is like this in Java. The name in sayHello (self.name) is similar to Javas (this.name).
Dear Frank, Thank you for explaining. Sorry for bothering again. if without using self the following program that i have tried is giving correct output then what is need to write self inside method. Secondly in this code shall we say that c is a local variable? it is clear to me that those variables which are inside class but outside method are called class variables but what about a and b. what term will be used for them?
Hi Sadia, no problem. The program is object oriented, you create the object 'm' of the type 'Coff'. self is just a variable name, it represents the instance object. In a functional program, there are no objects.
Good question. The variables a and b are parameters because we put them in the definition: addBeans(self,a,b). Variable c can be called local variable or a method variable, because it exists only in addBeans().
Hi Frank.
please if you tell me what is Solver().demo()? i know demo method is gonna call by class Solver but to call method object of class is made and then through it method is called. why i am getting error if i replace this line with these lines: obj=Solver(); obj.demo(); I know through class name we can access methods and class attributes but why () with Solver ?
Hi, you could do this:
I added a check to test if d is negative. Sqrt on negative numbers is impossible without the use of imaginary numbers. As you using a quadratic equation I think you want to use real numbers. If you enter a=2, b=4, c=-4 you will get the two roots.
Please explain me about "self". Is it a keyword?
self is not a keyword. You can use self.x to access the object attribute x inside a class.
For illustration, if you have an object named car with a variable name, you can access the attribute with self.name inside the class methods. The statements in the class methods will be applied to all variables of newly created objects. If we define self.driver = 'Shiney', all newly created objects will have a driver named Shiney. To set a variable for a single object you would use instanceName.driver = x or instanceName.setDriver(x)
Hello!
I don't understand yet the word "self". In the following example, the code didn't work until I put the word "self" on the argument of the function "Imprimir"
why do I have to take "self" as argument in every function?
Without using the self keyword you are using local variables. Local variables cannot be accessed outside the functions, because of the scope of the variable.
For illustration, consider this code:
The variable onlyInScope can only be accessed within __init__(). Adding the self keyword makes them accessibly outside by newly created objects. Adding self will tell Python these are class variables.