Python Tutorials
Python File Handling
Python Modules
Python is an object-oriented programming language.
Almost everything in Python is an object, with its structures and methods.
A class is like an architect, or a "plan" for creating things.
To create a class, use the keywords class
:
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
We can now use a class called MyClass to create objects:
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
The examples above are classes and objects in their simplest form, and are not really helpful in real-life applications.
To understand the meaning of classes we must understand __init __ () the built-in function.
All classes have a function called __init __ (), which is used every time a class is started.
Use the __init __ () function to assign values to object properties, or other functions that need to be performed when an object is created:
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John",
36)
print(p1.name)
print(p1.age)
Note: The __init__ ()
function is automatically called every time a class is used to create something new.
Items may contain paths. Methods in objects are functions that are part of an object.
Let's build a path in the Classroom:
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John",
36)
p1.myfunc()
Note: The self
parameter itself is a reference to the current class model, and is used for class flexible access.
The self
parameter itself is a reference to the current class model, and is used for class flexible accessibility.
It doesn't have to be named self
, you can call it whatever you like, but it should be the first parameter of any class activity:
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John",
36)
p1.myfunc()
You can change the properties for things like:
Set the age of p1 to 40:
p1.age = 40
You can remove structures from objects by using the keyword del
:
Delete the age property from the p1 object:
del p1.age
You can delete items by using the keyword del
:
Delete the p1 object:
del p1
class
descriptions can not be empty, but if for some reason you have a class
description that does not contain content, include a pass
statement to avoid finding an error.
class Person:
pass