Ascii() Built-in Function In Python

Function Name:

ascii(object)

Function Overview:

The ascii() method returns a printable string representation of a Python object.

The ascii() method actually calls the __repr__() method of the object passed which in turn returns the printable representation.

If __repr__() is not implemented for a class python will give a meaningful string representation comprising of the fully qualified type name and the address of the object.

Example:<asciitest.Student object at 0x100769898>

As per the Python requirements when a developer implements the __repr__() method for a user defined class,

  • the method has to return a string containing an expression with which an object with the same values can be recreated. 
  • when the above requirement can't be fulfilled the __repr__() can return<useful description of the object> in the form a string. It is better to make this string as rich as possible in terms of the information it conveys to the developer so that it aids in the debugging process.

 

Example python program using ascii(object):

class Student:

    myId = 0

   

    def __init__(self, aId_in):

        self.myId = aId_in

       

    def __repr__(self):

        return "Student({})".format(self.myId)

 

Output of the example python program using ascii(object):

myMac:Samples me$python

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> from asciitest import Student

>>> s1=Student(123)

>>> s2=eval(ascii(s1))

>>> s2.myId

123

 


Copyright 2019 © pythontic.com