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.

Create a Class

To create a class, use the keyword class:

class Devdojo:
  x = 5

print(Devdojo)

Create Object

Now we can use the class named myClass to create objects:

class Devdojo:
  x = 5

p1 = Devdojo()
print(p1.x)

the __init__() function

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

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

p1 = Person("John", 36)

print(p1.name) #john
print(p1.age)  #36

Object Methods

Objects can also contain methods. Methods in objects are functions that belongs to the object.

Let us create a method in the Person class:

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() # Hello my name is john

Modify Object Properties

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.age = 40

print(p1.age) #40

Delete Object Properties

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)

del p1.age

print(p1.age) #AttributeError: 'Person' object has no attribute 'age'

From w3schools Python


Login

or Sign Up

Sign Up

or Login
×
Want to create your own SAAS?

I can teach you to create your own Software as a Service. Click here to learn more!

Visit SAAS Adventure!