1901030012-MIT-自学 lecture8

学员信息

  • 学号: 1901030012
  • 学习内容: MIT第8课视频文稿p9-10 slide p12-16
  • 学习用时: 66min Notes no.: Day38

学习笔记

  1. convention
    So by convention, it’s a lot easier to do the one on the left.
    And as I mentioned, Python implicitly says, if you’re doing the one on the left, you can call this method on a particular object and it’s going to look up the type of the object and it’s going to essentially convert this on the left to the one on the right.
    def distance(self, other):
    code here
Using the class:
- [ ] conventional way - [ ] equivalent to
c = Coordinate(3,4) c = Coordinate(3,4)
zero = Coordinate(0,0) zero = Coordinate(0,0)
print(c.distance(zero)) print(Coordinate.distance(c, zero)

object to call method on c, name of method is distance and parameters not including self (self is implied to be c).

  1. informative debugging tool–str method
    So if you create a coordinate object, C is equal to coordinate 3, 4, right? That’s what we’ve done so far. If you print C, you get this funny message.
    Very uninformative, right? It basically says, well, C is an object of type coordinate at this memory location in the computer. Which is not what you wanted at all, right? Maybe you wanted to know what the values for x and y were. That would be a lot more informative. So by default, when you create your own type, when you print the object of that type, Python tells you this sort of information which is not what you want. So what you need to do is you need to define your own method that tells Python what to do when you call print on an object of this type.

c = Coordinate(3,4)
print(c)<main.Coordinateobject at
0x7fa918510488>

  • define a str method for a class.
  • Python calls the str method when used with print on your class object.
  • you choose what it does! Say that when we print a Coordinate object, want to show:

    print(c)
    <3,4>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Coordinate(object):
    def __init__(self, x, y):
    self.x = x
    self.y = y
    def distance(self, other):
    x_diff_sq = (self.x - other.x) ** 2
    y_diff_sq = (self.y - other.y) ** 2
    return (x_diff_sq + y_diff_sq) ** 0.5
    def __str__(self):
    return "<" + str(self.x) + "," + str(self.y) + ">"
  1. 我来实验一下啊,我怎么不能换行(据说是要空两个空格啊)呢?还有就是最最最简单的图表怎么就是搞不定呢?(不是搞不定,是眼睛无比的粗心大意,,,使劲盯着看,,,我舅说的没错,规范啊规范很重要,那就盯着盯着的不就找出来不同了)。然而,这个列表的点点是怎么输入进去的呢?!让我再纠结一会儿吧。