对不起,我刚开始学习python不久,我被这个程序代码卡住了,我只是不能让它像它应该的那样工作。
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)
我想知道狗主人的名字,但是我得到的是:
= RESTART: C:/Coding Practice/Object Oriented Programming.py =
<__main__.Person object at 0x000002C5DFB02050>
请帮忙。
您可以使用__str__
或__repr__
以更易于人类阅读的格式获取所有对象的属性。
__str__
(读作"dunder(双下划线)string")和__repr__
(读作"dunder-repper"(用于"表示"))都是基于对象的状态返回字符串的特殊方法。.
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
如果打印一个对象,或将其传递给format、str.format或str,则如果astr方法定义时,该方法将被调用,否则,repr
repr
repr方法由内置函数repr调用,是什么在python shell中对表达式求值时回显返回一个对象。
当您分配self.owner = owner
self时。owner存储owner对象的引用,您应该通过提及属性self.owner = owner.name
来访问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)
应该将__repr__
和__str__
方法添加到Person类中。或者只是__repr__
。
class Person:
def __init__(self,name):
self.name=name
def __repr__(self)
return str(self.name)