Exercise 2

class Clock(object):
    def __init__(self, time):
        self.time = time
    def print_time(self):
        print(self.time)

boston_clock = Clock('5:30')
paris_clock = boston_clock
paris_clock.time = '10:30'
boston_clock.print_time()

What does the code print out? '10:30'

Explanation:

boston_clockand paris_clockare two names for the same object. This is called aliasing.

因为list 是 mutable,所以改变b之后,a也相应改变。如果碰到不可改变的,则情况不同。

Exercise 3

class Weird(object):
    def __init__(self, x, y): 
        self.y = y
        self.x = x
    def getX(self):
        return x 
    def getY(self):
        return y

class Wild(object):
    def __init__(self, x, y): 
        self.y = y
        self.x = x
    def getX(self):
        return self.x 
    def getY(self):
        return self.y

X = 7
Y = 8

w1 = Weird(X, Y)
print(w1.getX())
print(w1.getY())

运行结果为:

Think about this: what is the difference between:

return self.x vs return x

解释:

When w1 is _instantiated _the x that is associated with the _instance _of w1 is assigned the value of 7. That 7 only exists within the context of w1, i.e._self._x. Nowhere is there a variable x that exists outside of the w1 object. So if you want to return the value of 7, you have to return _self._x (as in Q3 and Q4). So the answer to these 2 questions is that it would generate an error. Specifically "NameError: name 'x' is not defined".

.

Exercise: int set

Add the appropriate method(s) so that len(s) returns the number of elements in s

参考文档

https://docs.python.org/3.3/reference/datamodel.html.

Exercise 4

当我们搞不清楚Hierarchies的时候,可以到 pythontutor.com 进行可视化

class A(object):
    def __init__(self):
        self.a = 1
    def x(self):
        print("A.x")
    def y(self):
        print("A.y")
    def z(self):
        print("A.z")

class B(A):
    def __init__(self):
        A.__init__(self)
        self.a = 2
        self.b = 3
    def y(self):
        print("B.y")
    def z(self):
        print("B.z")

class C(object):
    def __init__(self):
        self.a = 4
        self.c = 5
    def y(self):
        print("C.y")
    def z(self):
        print("C.z")

class D(C, B):
    def __init__(self):
        C.__init__(self)
        B.__init__(self)
        self.d = 6
    def z(self):
        print("D.z")

obj = D()
print(obj.a)
obj.y()

results matching ""

    No results matching ""