Class and object in Python - ProgrammerTech
Language:

Search

Class and object in Python

  • Share this:
Class and object in Python

Class concept in Python

Class is a container that you can put inside this container variables, arrays, functions, etc... In order to define a new class, we write the word class and then give it a name. The class name must start with a capital letter to distinguish it, then we put a colon.

Example 1

class Age:
    x = 28

We created a class named Age and then created a variable x with a value of 28.

Example 2

Create a simple Class named MyCs with an x ​​value of 5.

class MyCs:
    x = 5

 

Object in Python

The object is a copy of the class, and to create a copy of a particular class we define a variable whose value is equal to the name of the class and then put parentheses. This object consists of methods. This object includes functions. We can write more than one function and make it include. Under the object, its function remains that it is responsible for these functions. Instead of calling each function alone, we call the object in the functions that contain them all.

Example 3

Create an object with the name pt and print the value of x from the previous class.

pt = MyCs()
print(pt.x)

Example 4

>>>class Info:
        def name (self):
            return "hello world"
        def age (self):
            return 26
>>>c = Info()
>>>c.name()
'hello world'
>>>c.age()
'26'

In the previous example, we created a class called Info, the class name must start with a capital letter exclusively for distinction, and we created a function named name and we gave it a value that returns it is hello world, and we created another function named age and returns us the value of 26.

The word return serves as the print function, and it returns the specified value to us, and we created a variable named c and assigned it the value of the Info class, and then we called the functions inside the class through the variable c that we created.

This is in the Python shell and we put return to the method in our previous example, but if it is a saved file, we replace it in print and write all the requests and then give run to print the output for us.

 

The word self in Python

When defining a function inside a class, Python forces you to put the word self or any other word as the first parameter in it, and then put the number of parameters you want, even if you do not intend to put any parameter in this function, you are forced to write the word self or any Another word for Parameter.

Most programmers put the word self as the first parameter in the function. It is better that you use it as well so that it works in the same way that most programmers around the world do.

The reason for putting the word self as the first parameter in the function is that the Python interpreter is able to access the properties of the same class, ie be a pointer to the class.

Example 5

class Comparison:
    def print_max(self, a, b):
        if a > b:
            print(a, 'is bigger')
        elif a < b:
            print(b, 'is bigger')
        else:
            print('They are equal')
comparison = Comparison()
comparison.print_max(4, 9)

We created a class called Comparison and put in it a function whose name was print_max and there are two parameters (a and b) in it and they noticed that we were forced to put self as the first parameter in the function even if we didn't need it and when calling the function we didn't care about it.

And when we run this code, it will print the result 9 because it is greater than 4.

9 is bigger

 

Function __init__()

The __init__ function must be defined just like any other function we define and between the function parentheses we can directly pass the names of the properties we want to put in the class and we want to give them initial values ​​directly when creating objects from the class.

Example 6

Create a class named Cs and use the __init__() function to set values ​​for name and age.

class Cs:
    def __init__(self, name, age):
        self.name = name
        self.age = age
pt = Cs("Saja", 25)
print(pt.name)
print(pt.age)

 

The constractor in Python

The general form of the constructor is by writing a class, and below this class, we write def, then we write the constructor function, which is __init__, then open parentheses and write self in it.

The general form of writing a constructor

class info:
   def __init__ (self):

Example 7

class info:
     def __init__ (self):
         print ("ahmed kaissar")
     def my_info (self):
         print ("database hack")
c = Info ()

If we run now, the result will be:

ahmed kaissar

We note that only the first method is printed for us, while the second method is printed only when summoned personally as follows

c.my_info()

Then it will be called to print.

Example 8

class Info:
    def __init__ (self, name = "kaissar", age = 21):
        self.name = name
    self.age = age 
    def my_info (self,data = "my data"):
        print (" hello world man ")
        print (data)
c = Info ("data", "26")
c.my_info ("my new data")
print (c.name)
print (c.age)
#عند عمل تشغيل للكود ستكون النتيجة
hello world man
my new data
data
26

The example is understandable to all and does not need explanation, and the result is clear we wrote.

Example 9

Create a class containing the constractor and another function.

class Cs:
    def __init__(mysillyobject, name, age):
        mysillyobject.name = name
        mysillyobject.age = age
def myfunc(abc):
    print("Hello my name is " + abc.name)
pt = Cs("Saja", 25)
pt.myfunc()

Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com