Printing classes in python

Python: Printing nested classes

You are aiming to have a string version of your objects. Python knows two methods for this: __repr__() and __str__() . The first is meant to be a string which, if interpreted as Python source, would re-generate the thing it represents. If you just call vars(x) you receive a dict of all fields in the given x . Most means to output this dict (and probably also yours) make it call the __repr__() function of each of its contents. That’s why you see that ugly string because that’s the __repr__() of your Shelf object.

I propose to implement it and thus override the standard implementation. You will have to do that in Shelf :

class Library(): def __init__(self): self.shelves = [] self.shelf = self.Shelf() class Shelf(): def __init__(self): self.books = [] def __repr__(self): return repr(vars(self)) x = Library() 

And while you’re at it, you could do the same in your Library as well; then typing x alone (i. e. instead of vars(x) ) would also give the nice output:

class Library(): def __init__(self): self.shelves = [] self.shelf = self.Shelf() def __repr__(self): return repr(vars(self)) class Shelf(): def __init__(self): self.books = [] def __repr__(self): return repr(vars(self)) x = Library() 

And of course you can refactor that out and put that aspect into a base class:

class Representer(object): def __repr__(self): return repr(vars(self)) class Library(Representer): def __init__(self): self.shelves = [] self.shelf = self.Shelf() class Shelf(Representer): def __init__(self): self.books = [] x = Library() 

Источник

Читайте также:  Csharp string to file

Print an Object of a Class in Python

  1. Print an Object in Python Using the __repr__() Method
  2. Print an Object in Python Using the __str__() Method
  3. Print an Object in Python by Adding New Class Method

In this tutorial, we will look into multiple methods to print a class object in Python. Suppose we want to print a class instance using the print() function, like viewing the object’s data or values. We can do so by using the methods explained below.

The __repr__() method returns the object’s printable representation in the form of a string. It, by default, returns the name of the object’s class and the address of the object.

When we print an object in Python using the print() function, the object’s __str__() method is called. If it is not defined then the __str__() returns the return value of the __repr__() method. That is why when we try to print an object of a user-defined class using the print() function, it returns the return value of the __repr__() method.

Therefore, we can define or override the __repr__() method to print an object’s summary or desired values.

Suppose we have a user-defined class ClassA with no __repr__() method, the below example code demonstrates the output when we try to print an object of the ClassA with no __repr__() method.

class classA():  def __init__(self):  self.var1 = 0  self.var2 = "Hello"  A = classA() print(A) 

As we have not defined the __repr__() method, it has by default returned the name of the class and address of the object.

Now, let’s define the __repr__() method of the class classA , and then use the print() function. The print() and print(repr()) should return the same value.

class classA():   def __init__(self):  self.var1 = 0  self.var2 = "Hello"   def __repr__(self):  return "This is object of class A"  A = classA() print(A) print(repr(A)) 
This is object of class A This is object of class A 

The __str__() method returns the string version of the object in Python. If an object does not have a __str__() method, it returns the same value as the __repr__() method.

We have seen in the above example codes, in case the __str__() method is not defined, the print() method prints the printable representation of the object using the __repr__() method.

Now, let’s define the __str__() method of our example class ClassA and then try to print the object of the classA using the print() function. The print() function should return the output of the __str__() method.

class classA():   def __init__(self):  self.var1 = 0  self.var2 = "Hello"   def __repr__(self):  return "This is object of class A"   def __str__(self):  print("var1 =", self.var1)  print("var2 =", end=" ")  return self.var2  A = classA() print(A) 

Another approach can be used instead of override or define the __str__() and __repr__() methods of the class. A new print() method can be described within the class, which will print the class attributes or values of our choice.

The below example code demonstrates how to define and then use the object.print() method to print an object in Python.

class classA():   def __init__(self):  self.var1 = 0  self.var2 = True  self.var3 = "Hello"   def print(self):  print("var1 =", self.var1)  print("var2 =", self.var2)  print("var3 =", self.var3)  A = classA() A.var2 = False A.print() 
var1 = 0 var2 = False var3 = Hello 

Related Article — Python Object

Источник

How To Print A List Of Class Objects In Python

To print a list of class objects in Python, you can use the for loop, join() function, or ‘*’ operator. Let’s see how to perform them.

To print a list of class objects, you have to print each attribute of the object in each iteration or override the __str__() method when creating the object first. Then, combined with the for loop, join() function or ‘*’ operator.

Using the for loop

A simple way to print a list of class objects in Python, you can use the for loop. It is used to iterate the loop and print out each element in the list.

Look at the example below.

# Create an object. class Club: def __init__(self, club, rank, point): self.name = club self.rank = rank self.point = point # Override def __str__(self): return self.name + ' ' + str(self.rank) + ' ' + str(self.point) # Create the list of objects. club1 = Club('MU', 1, 40) club2 = Club('ARS', 2, 39) club3 = Club('LIV', 3, 38) clubs = [club1, club2, club3] # Print a list of clubs with the for loop. for element in clubs: print(element)
MU 1 40 ARS 2 39 LIV 3 38

Using the ‘*’ operator

If you want to print all elements of class objects that are one whitespace apart, you can use the ‘*’ operator.

Look at the example below.

# Create an object. class Club: def __init__(self, club, rank, point): self.name = club self.rank = rank self.point = point # Override def __str__(self): return self.name + ' ' + str(self.rank) + ' ' + str(self.point) # Create the list of objects. club1 = Club('MU', 1, 40) club2 = Club('ARS', 2, 39) club3 = Club('LIV', 3, 38) clubs = [club1, club2, club3] # Print a list of clubs with the '*' operator. print(*clubs)
MU 1 40 ARS 2 39 LIV 3 38

Using the join() function

Besides, you can use the join() function to print a list of class objects with the specified distinction between two continuous elements. To perform it, you have to convert the object to the String first.

Look at the example below.

# Create an object. class Club: def __init__(self, club, rank, point): self.name = club self.rank = rank self.point = point # Override def __str__(self): return self.name + ' ' + str(self.rank) + ' ' + str(self.point) # Create the list of objects. club1 = Club('MU', 1, 40) club2 = Club('ARS', 2, 39) club3 = Club('LIV', 3, 38) clubs = [club1, club2, club3] # Convert the Club to the String. clubs = [str(x) for x in clubs] # Print a list of clubs with the join() function. print(' || '.join(clubs))
MU 1 40 || ARS 2 39 || LIV 3 38

Summary

We have shown you how to print a list of class objects in Python in 3 ways. In our opinion, you should use the join() function because you can assign the specified distinction between two continuous elements with this function. We hope this tutorial is helpful to you. Thanks!

My name is Thomas Valen. As a software developer, I am well-versed in programming languages. Don’t worry if you’re having trouble with the C, C++, Java, Python, JavaScript, or R programming languages. I’m here to assist you!

Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Java, Python, JavaScript, R

Источник

How to print objects of class using print function in Python

  • All categories
  • ChatGPT (11)
  • Apache Kafka (84)
  • Apache Spark (596)
  • Azure (145)
  • Big Data Hadoop (1,907)
  • Blockchain (1,673)
  • C# (141)
  • C++ (271)
  • Career Counselling (1,060)
  • Cloud Computing (3,469)
  • Cyber Security & Ethical Hacking (162)
  • Data Analytics (1,266)
  • Database (855)
  • Data Science (76)
  • DevOps & Agile (3,608)
  • Digital Marketing (111)
  • Events & Trending Topics (28)
  • IoT (Internet of Things) (387)
  • Java (1,247)
  • Kotlin (8)
  • Linux Administration (389)
  • Machine Learning (337)
  • MicroStrategy (6)
  • PMP (423)
  • Power BI (516)
  • Python (3,193)
  • RPA (650)
  • SalesForce (92)
  • Selenium (1,569)
  • Software Testing (56)
  • Tableau (608)
  • Talend (73)
  • TypeSript (124)
  • Web Development (3,002)
  • Ask us Anything! (66)
  • Others (2,231)
  • Mobile Development (395)
  • UI UX Design (24)

Join the world’s most active Tech Community!

Welcome back to the World’s most active Tech Community!

Subscribe to our Newsletter, and get personalized recommendations.

GoogleSign up with Google facebookSignup with Facebook

Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

  • DevOps Certification Training
  • AWS Architect Certification Training
  • Big Data Hadoop Certification Training
  • Tableau Training & Certification
  • Python Certification Training for Data Science
  • Selenium Certification Training
  • PMP® Certification Exam Training
  • Robotic Process Automation Training using UiPath
  • Apache Spark and Scala Certification Training
  • Microsoft Power BI Training
  • Online Java Course and Training
  • Python Certification Course
  • Data Scientist Masters Program
  • DevOps Engineer Masters Program
  • Cloud Architect Masters Program
  • Big Data Architect Masters Program
  • Machine Learning Engineer Masters Program
  • Full Stack Web Developer Masters Program
  • Business Intelligence Masters Program
  • Data Analyst Masters Program
  • Test Automation Engineer Masters Program
  • Post-Graduate Program in Artificial Intelligence & Machine Learning
  • Post-Graduate Program in Big Data Engineering

COMPANY

WORK WITH US

DOWNLOAD APP

appleplaystore googleplaystore

CATEGORIES

CATEGORIES

  • Cloud Computing
  • DevOps
  • Big Data
  • Data Science
  • BI and Visualization
  • Programming & Frameworks
  • Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy

Источник

printing the instance in Python

class Complex: def init(self, realpart, imagpart): self.real = realpart self.imag = imagpart print self.real, self.imag I get this output:

I hope you understand that this code will just print the two variables, and not the constructor. It’s the IDLE that is printing the returned object.

4 Answers 4

You running the code from an interactive python prompt, which prints out the result of any statements, unless it is None .

>>> 1 1 >>> 1 + 3 4 >>> "foobar" 'foobar' >>> 

So your call to Complex(3,2) is creating an object, and python is printing it out.

Because class constructor always return instance, then you could call its method after that

inst = Complex(3,2) inst.dosomething() 

Because it is the result of the statement «Complex(3,2)». In other words, a Complex object is being returned, and the interactive interpreter prints the result of the previous statement to the screen. If you try «c = Complex(3, 2)» you will suppress the message.

What you want is to define __str__(self) and make it return a string representation (not print one).

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.24.43543

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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