Why isn't printing? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why isn't printing? (/thread-39707.html) |
Why isn't printing? - SpookyStuff - Mar-29-2023 class Dog: def __init__(self, breed, age, color, is_mixed): self.breed = breed self.age = age self.color = color self.is_mixed = is_mixed dog1 = Dog("Border Collie", 3, "white", True) dog2 = Dog("Golden Retriever", 0.5, "brown", False) dog3 = Dog("Poodle", 5, "black", True) print(dog2.breed) #iisn't printing RE: Why isn't printing? - deanhystad - Mar-29-2023 What makes you think it doesn't print? How do you run the program? Where are you looking for output? There are no errors in the program. It works fine for me. You should add a __str__() method to your class so you can print a description of the dog. Like this: class Dog: def __init__(self, breed, age, color, is_mixed): self.breed = breed self.age = age self.color = color self.is_mixed = is_mixed def __str__(self): if self.is_mixed: return f"Dog: {breed} mix, color={self.color}, age={self.age}" return f"Dog: {breed}, color={self.color}, age={self.age}" dogs = ( Dog("Border Collie", 3, "white", True), Dog("Golden Retriever", 0.5, "brown", False), Dog("Poodle", 5, "black", True), ) print(*dogs, sep="\n") Or you could make this a dataclass. Using the dataclass decorator adds several features to your class. It writes the __init__() method for you. It provides a good __str__() method (actually it is a __repr__() method that is a lot like __str__(), It provides comparison operators. Not terribly important for a Dog class, but you could use it to srot the dogs by breed (fields are used when making comparisons). It also does type checking. It will not let you make a Dog that is "brown" years old and has 3.5 hair (mix up order of arguments when creating object).from dataclasses import dataclass. @dataclass class Dog: breed: str age: float color: str is_mixed: bool = False # Assume False unless otherwise specified dogs = ( Dog("Border Collie", 3, "white", True), Dog("Golden Retriever", 0.5, "brown"), Dog("Poodle", 5, "black", True), ) print(*dogs, sep="\n") You can read about dataclasses here: https://docs.python.org/3/library/dataclasses.html
RE: Why isn't printing? - buran - Mar-29-2023 (Mar-29-2023, 06:39 PM)SpookyStuff Wrote: #iisn't printingthe code works just fine. it prints Golden Retriever
|