Monday, May 15, 2023

#PYTHON(DAY19)class and object,_init_(),_str_() functions

 

#PYTHON(DAY19)

classes and objects

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a “blueprint” for creating objects.

syntax

class classname():
pass

creating object of a class

Now, we can use class name to create a object

x = classname()
print(type(x))

Example

class sample:
x=5
print(sample)

And the output is:

<class '__main__.sample'>
y = sample()
print(y.x)

And the output is:

5

The __init__() Function

  • init: is a special method, with a clear and definite functionality to assign values to our object properties and methods that might require these values, and in whole are require to create an object
  • note class functions that start with’__’ are called as special methods. They executes a pre-defined functionality.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

And the output is:

John
36

The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.

If the __str__() function is not set, the string representation of the object is returned:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

And the output is:

John(36)

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...