热线电话:13121318867

登录
2018-12-14 阅读量: 824
如何定义类?

如何使它们适用于我们自己定义的类?

如果我们需要调试的详细信息,用户定义的类也应该有一个__repr__。如果我们认为为用户提供字符串版本会很有用,我们会创建一个__str__函数。

# Python program to demonstrate writing of __repr__ and

# __str__ for user defined classes

# A user defined class to represent Complex numbers

class Complex:

# Constructor

def __init__(self, real, imag):

self.real = real

self.imag = imag

# For call to repr(). Prints object's information

def __repr__(self):

return 'Rational(%s, %s)' % (self.real, self.imag)

# For call to str(). Prints readable form

def __str__(self):

return '%s + i%s' % (self.real, self.imag)

# Driver program to test above

t = Complex(10, 20)

print str(t) # Same as "print t"

print repr(t)

print语句和str()内置函数使用__str__显示对象的字符串表示形式,而repr()内置函数使用__repr__显示对象。

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子