Site icon i2tutorials

Python Method Objects

Python Method Objects

In this tutorial, we will learn python in detail.

 

Object is an instance of a class. Objects can contain methods.

An object consists of :

 

Example:

 

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("Peter", 36)
p1.myfunc()

 

Output:

 

Hello my name is Peter

 

Self parameter is used to access variables that belong to class. It need not to be named self always, you can call it whatever you like, but it has to be the first parameter of any function in the class.

 

Example:

 

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("Peter", 36)
p1.myfunc()

 

Output:

 

Hello my name is Peter

 

You can modify object properties. It is as shown below.

 

Example:

 

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("Peter", 40)

p1.age = 50

print(p1.age)

Output:

 

50

 

You can delete object properties using the del keyword

 

Example:

 

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("Peter", 40)

del p1.age

print(p1.age)

 

Output:

 

Traceback (most recent call last):
File "demo_class7.py", line 13, in <module>
    print(p1.age)
AttributeError: 'Person' object has no attribute 'age'

 

You can also delete objects using the del keyword.

 

Example:

 

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("Peter", 40)

del p1

print(p1)

 

Output:

 

Traceback (most recent call last):
File "demo_class8.py", line 13, in <module>
    print(p1)
NameError: 'p1' is not defined
Exit mobile version