【CS 61a study notes 6】Representation & Linked list & Efficiency & Sets

Representation

String conversion

To represent data effectively, an object value should behave like the kind of data it is meant to represent ,including producing a string representation of itself. String representations of data values are especially important in aninteractive language that automatically displays the string representation of the values of expressions in an interative session.
Python stipulates that all objects should produce two different string representations: one that is human-interpretable text and one that is a Python-interpretable expression.
The constructor function for strings , str, returns a human-readable string. Where the repr function returns a Python expression that evaluates to an equal object .
repr(object) => string : return the cannoical string representation of the object . For most object types , eval(repr(object)) == object

  • The result of calling repr on the value of an expression is what python prints in an interactive session.
>>> 12e12
12000000000000.0
>>> print(repr(12e12))
12000000000000.0
  • The str constructor often coinsides with repr , but provides a more interpretable text presentation in some cases
>>> from datetime import date
>>> tues = date(2011, 9, 12)
>>> repr(tues)
'datetime.date(2011, 9, 12)'
>>> str(tues)
'2011-09-12'
  • The repr function always invokes a method called _repr_ on its argument
  • The str constructor is implemented in a similar manner: it invokes a method call _str_ on its argument.
class Bear1():
    """ a bear"""
    def __repr__(self):
        return '__repr__ Bear1()'
     

oski1 = Bear1()
print(oski1)
print(str(oski1))
print(repr(oski1))
print(oski1.__repr__()) # <bound method Bear1.__repr__ of __repr__ Bear1()>
print(oski1.__str__()) # <method-wrapper '__str__' of Bear1 object at 0x0000019C1C5E1488>

# the ans is:
# __repr__ Bear1()
# __repr__ Bear1()
# __repr__ Bear1()
# __repr__ Bear1()
# __repr__ Bear1()

print('===================='*2)

class Bear2():
    """ a bear"""
    def __repr__(self):
        return '__repr__ Bear2()'
        
    def __str__(self):
        return '__str__ a Bear2'
     

oski2 = Bear2()
print(oski2)  # print __str__
print(str(oski2)) # print __str__
print(repr(oski2))
print(oski2.__repr__()) # <bound method Bear2.__repr__ of __repr__ Bear2()>
print(oski2.__str__()) # <bound method Bear2.__str__ of __repr__ Bear2()>

print(oski2.__repr__) 
print(oski2.__str__)

# the ans is 
# __str__ a Bear2
# __str__ a Bear2
# __repr__ Bear2()
# __repr__ Bear2()
# __str__ a Bear2


print('===================='*2)

class Bear3():
    """ a bear"""
    def __init__(self):
        # instance attribute
        self.__repr__ = lambda : 'self.__repr__ oski3'
        self.__str__ = lambda : 'self.__str__ this bear3'
        
    def __repr__(self):
        return '__repr__ Bear3()'
        
    def __str__(self):
        return '__str__ a Bear3'
     

oski3 = Bear3()
print(oski3)  # always same as str(oksi3)
print(str(oski3)) #skip the instance attribute of the oski3 and go strait to the class
print(repr(oski3)) # ignore the instance of the oski3

# the following two are the conventional way
print(oski3.__repr__()) # <function Bear3.__init__.<locals>.<lambda> at 0x00000255A41F51F8>
print(oski3.__str__()) # <function Bear3.__init__.<locals>.<lambda> at 0x00000255A4245DC8>


# this ans is :
# __str__ a Bear3
# __str__ a Bear3
# __repr__ Bear3()
# self.__repr__ oski3
# self.__str__ this bear3

Special Methods

  • _init_ method of a class is automatically invoked whenever an object is contructed
  • The _str_ method is invoked automatically when printing , and the _repr_ is invoked in an interative session to display values
  • True and False value
    • 0 is false value and all other numbers are true values
    • By default, objects of user-defined classes are considered to be true, but the special _bool_ method can be used to override this behavior.
    • If an object defines the _bool_ method, then the python calls that method to determine its truth value.
    • Suppose we want a bank account with 0 balance to be false ,we can set: Account.__bool__ = lambda self: self.balance != 0
>>> bool(Account('Jack'))
False
>>> if not Account('Jack'):
        print('Jack has nothing')
Jack has nothing
  • Sequence Operations:
    • the len function invoked the _len_ method of its argument to determine its lenth.
    • The _getitem_ method is invoked by the element selection operator(often using square brackets) , but it can also be invoked directly.
>>> x = 'test'
>>> x.__len__()
4
>>> len(x)
4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值