Printing objects in python

How to print instances of a class using print()?

How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)? See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than or similar). (In fact, the technique is essentially the same, but trickier to apply.)

12 Answers 12

>>> class Test: . def __repr__(self): . return "Test()" . def __str__(self): . return "member of Test" . >>> t = Test() >>> t Test() >>> print(t) member of Test 

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__ , Python will use what you see above as the __repr__ , but still use __str__ for printing.

Читайте также:  Javascript изменить значение атрибута

there’s also a unicode method, which you can use instead of Str ; note that it should return a unicode object, not a string (but if you return a string, the conversion to unicode will be done anyway. )

@kender — I didn’t know about it, but in retrospect it makes perfect sense given Python 2.x’s broken Unicode handling.

Saved me! However, after re-implementing the method __repr__(self), print will mislead users. Are you aware of any best practices around this?

As Chris Lutz explains, this is defined by the __repr__ method in your class.

From the documentation of repr() :

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() , otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

Given the following class Test:

class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return f" b:>" def __str__(self): return f"From str method of Test: a is , b is " 

..it will act the following way in the Python shell:

>>> t = Test(123, 456) >>> t >>> print(repr(t)) >>> print(t) From str method of Test: a is 123, b is 456 >>> print(str(t)) From str method of Test: a is 123, b is 456 

If no __str__ method is defined, print(t) (or print(str(t)) ) will use the result of __repr__ instead

If no __repr__ method is defined then the default is used, which is roughly equivalent to:

def __repr__(self): cls = self.__class__ return f". object at >" 

Источник

How to print an object in Python

Example 3: print() with file parameter In Python, you can print objects to the file by specifying the file parameter. If you are having trouble with buffering, you can flush the output by adding keyword argument: Python 2.6 and 2.7 From Python 2.6 you can either import the function from Python 3 using the module: which allows you to use the Python 3 solution above.

Python print()

In this tutorial, we will learn about the Python print() function with the help of examples.

The print() function prints the given object to the standard output device (screen) or to the text stream file.

Example
message = 'Python is fun' 
# print the string message print(message)
# Output: Python is fun

The full syntax of print() is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
  • objects — object to the printed. * indicates that there may be more than one object
  • sep — objects are separated by sep. Default value : ‘ ‘
  • end — end is printed at last
  • file — must be an object with write(string) method. If omitted, sys.stdout will be used which prints objects on the screen.
  • flush — If True, the stream is forcibly flushed. Default value : False

Note: sep , end , file , and flush are keyword arguments. If you want to use sep argument, you have to use:

print(*objects, sep = 'separator')

It doesn’t return any value; returns None .

Example 1: How print() works in Python?

print("Python is fun.") a = 5 # Two objects are passed 
print("a =", a)
b = a # Three objects are passed
print('a =', a, '= b')
Python is fun. a = 5 a = 5 = b

In the above program, only the objects parameter is passed to print() function (in all three print statements).

  • ‘ ‘ separator is used. Notice the space between two objects in the output.
  • end parameter ‘\n’ (newline character) is used. Notice, each print statement displays the output in the new line.
  • file is sys.stdout . The output is printed on the screen.
  • flush is False . The stream is not forcibly flushed.

Example 2: print() with separator and end parameters

a = 5 
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')

We passed the sep and end parameters in the above program.

Example 3: print() with file parameter

In Python, you can print objects to the file by specifying the file parameter.

Recommended Reading: Python File I/O

sourceFile = open('python.txt', 'w') print('Pretty cool, huh!', file = sourceFile) sourceFile.close()

This program tries to open the python.txt in writing mode. If this file doesn’t exist, python.txt file is created and opened in writing mode.

Here, we have passed sourceFile file object to the file parameter. The string object ‘Pretty cool, huh!’ is printed to the python.txt file (check it in your system).

Finally, the file is closed using the close() method.

Python — How to print the full NumPy array, without, Suppose you have a numpy array. arr = numpy.arange (10000).reshape (250,40) If you want to print the full array in a one-off way (without toggling np.set_printoptions), but want something simpler (less code) than the context manager, just do. for row in arr: print row.

How to print an object in Python

When I print $ dict of myobject, it returns:

I want it to return a dict of myobject and all objects inside my object change to dict too:

If you are the creator of DEMO.Detail , you could add __repr__ and __str__ methods:

class Detail: def __str__(self): return "string shown to users (on str and print)" def __repr__(self): return "string shown to developers (at REPL)" 

This will cause your object to function this way:

>>> d = Detail() >>> d string shown to developers (at REPL) >>> print(d) string shown to users (on str and print) 

In your case I assume you’ll want to call dict(self) inside __str__ .

If you do not control the object, you could setup a recursive printing function that checks whether the object is of a known container type ( list , tuple , dict , set ) and recursively calls iterates through these types, printing all of your custom types as appropriate.

There should be a way to override pprint with a custom PrettyPrinter. I’ve never done this though.

Lastly, you could also make a custom JSONEncoder that understands your custom types. This wouldn’t be a good solution unless you actually need a JSON format.

>>> import pprint >>> a = > >>> pprint.pprint(a) > 

If your objects have __repr__ implemented, it can also print those.

import pprint class Cheetah: def __repr__(self): return "chirp" zoo = > pprint.pprint(zoo) # Output: > 

Python String Format – Python S Print Format Example, print («Steve plays <0>and .».format («trumpet», «drums»)) We can modify this example and switch the index numbers in the string. You will notice that the sentence has changed and the placement of the arguments is switched. print («Steve plays and <0>.».format («trumpet», «drums»)) Keyword arguments

Python print bytes

I’m using a python3 program for binary exploitation, but it’s not printing bytes correctly.

import struct padding = b"AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZ" ret = struct.pack("I", 0x55619d84) payload = b"\xCC" print (padding+ret+payload, sep="", end="") 

but hexdump gives me this

00000000 62 27 41 41 41 41 42 42 42 42 43 43 43 43 44 44 |b'AAAABBBBCCCCDD| 00000010 44 44 45 45 45 45 46 46 46 46 47 47 47 47 48 48 |DDEEEEFFFFGGGGHH| 00000020 48 48 49 49 49 49 4a 4a 4a 4a 4b 4b 4b 4b 4c 4c |HHIIIIJJJJKKKKLL| 00000030 4c 4c 4d 4d 4d 4d 4e 4e 4e 4e 4f 4f 4f 4f 50 50 |LLMMMMNNNNOOOOPP| 00000040 50 50 51 51 51 51 52 52 52 52 53 53 53 53 54 54 |PPQQQQRRRRSSSSTT| 00000050 54 54 55 55 55 55 56 56 56 56 57 57 57 57 58 58 |TTUUUUVVVVWWWWXX| 00000060 58 58 59 59 59 59 5a 5a 5a 5a 5c 78 38 34 5c 78 |XXYYYYZZZZ\x84\x| 00000070 39 64 61 55 5c 78 63 63 27 |9daU\xcc'| 00000079 

As you can see, it’s not encoded properly. Starts with b ‘ , address is not properly encoded etc.

What’s wrong with my code ? Thank you

Solved. Had to use sys.stdout.buffer.write(x) instead of print(x). Thank you @ChrisB

JSON Pretty Print using Python, Syntax: json.dumps(obj, indent,separator) Parameter: obj: Serialize obj as a JSON formatted stream indent: If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. …

How to print without a newline or space

Источник

Convention to print an object in python

Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging. is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives?

4 Answers 4

You can overwrite either the __str__ or the __repr__ method.

There is no convention on how to implement the __str__ method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the __repr__ method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e. eval(repr(obj)) == obj .

Assuming you have a class Point , __str__ and __repr__ could be implemented like this:

class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(%.2f, %.2f)" % (self.x, self.y) def __repr__(self): return "Point(x=%r, y=%r)" % (self.x, self.y) def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y 
>>> p = Point(0.1234, 5.6789) >>> str(p) '(0.12, 5.68)' >>> "The point is %s" % p # this will call str 'The point is (0.12, 5.68)' >>> repr(p) 'Point(x=0.1234, y=5.6789)' >>> p # echoing p in the interactive shell calls repr internally Point(x=0.1234, y=5.6789) >>> eval(repr(p)) # this echos the repr of the new point created by eval Point(x=0.1234, y=5.6789) >>> type(eval(repr(p))) >>> eval(repr(p)) == p True 

Источник

How to print a list, dict or collection of objects, in Python

I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function? Here’s the class:

class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -> [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index] 

2 Answers 2

Yes, you need to use __repr__ . A quick example of its behavior:

>>> class Foo: . def __str__(self): . return '__str__' . def __repr__(self): . return '__repr__' . >>> bar = Foo() >>> bar __repr__ >>> print bar __str__ >>> repr(bar) '__repr__' >>> str(bar) '__str__' 

However, if you don’t define a __str__ , it falls back to __repr__ , although this isn’t recommended:

>>> class Foo: . def __repr__(self): . return '__repr__' . >>> bar = Foo() >>> bar __repr__ >>> print bar __repr__ 

All things considered, as the manual recommends, __repr__ is used for debugging and should return something repr esentative of the object.

Источник

Оцените статью