Home > Blockchain >  Can't print an object from a class
Can't print an object from a class

Time:06-27

sorry but I just started learning python not too long ago and I'm stuck in thisprogram code, I just can't get it to work like it should.

class Dog():
    def __init__(self,name,breed,owner):
        self.name = name
        self.breed = breed
        self.owner = owner

class Person():
    def __init__(self,name):
        self.name = name


mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner)

I want to get the dog's owner name but all I get is this:

= RESTART: C:/Coding Practice/Object Oriented Programming.py =
<__main__.Person object at 0x000002C5DFB02050>

Help would be appreciated.

CodePudding user response:

You can use __str__ or __repr__ to get all the object's attributes in a more human-readable format.

__str__ (read as "dunder (double-underscore) string") and __repr__ (read as "dunder-repper" (for "representation")) are both special methods that return strings based on the state of the object.

 class Dog():
    def __init__(self,name,breed,owner):
        self.name = name
        self.breed = breed
        self.owner = owner
    
    def __str__(self):
        return  str(self.__class__)   '\n'  '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

    
class Person():
    def __init__(self,name):
        self.name = name
    
    def __str__(self):
        return  str(self.__class__)   '\n'  '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog", mick)
print(dog.owner)

str

If you print an object, or pass it to format, str.format, or str, then if a str method is defined, that method will be called, otherwise, repr will be used.

repr

The repr method is called by the builtin function repr and is what is echoed on your python shell when it evaluates an expression that returns an object.

CodePudding user response:

when you assign self.owner = owner self.owner stores the reference of owner object you should access the name value by mentioning the attribute self.owner = owner.name.

class Dog():
    def __init__(self,name,breed,owner):
        self.name = name
        self.breed = breed
        self.owner_name = owner.name

class Person():
    def __init__(self,name):
        self.name = name


mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner_name)

CodePudding user response:

You should add __repr__ and __str__ methods to the Person class. Or just __repr__.

class Person:
    def __init__(self,name):
        self.name=name
    def __repr__(self)
        return str(self.name)
  • Related