首页 > 代码库 > Python 学习笔记(3)

Python 学习笔记(3)

Class:

 

def scope_test():    def do_local():        spam = "local spam"    def do_nonlocal():        nonlocal spam        spam = "nonlocal spam"    def do_global():        global spam        spam = "global spam"    spam = "test spam"    do_local()    print("After local assignment:", spam)    do_nonlocal()    print("After nonlocal assignment:", spam)    do_global()    print("After global assignment:", spam)scope_test()print("In global scope:", spam)

The output of the example code is:

After local assignment: test spamAfter nonlocal assignment: nonlocal spamAfter global assignment: nonlocal spamIn global scope: global spam


class MyClass:    """A simple example class"""    i = 12345    def f(self):        return ‘hello world‘


So in our example, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. But x.f is not the same thing as MyClass.f — it is a method object, not a function object.

In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

 

 

shared data can have possibly surprising effects with involving mutableobjects such as lists and dictionaries. For example, the tricks list in the following code should not be used as a class variable because just a single list would be shared by all Dog instances:

class Dog:    tricks = []             # mistaken use of a class variable    def __init__(self, name):        self.name = name    def add_trick(self, trick):        self.tricks.append(trick)>>> d = Dog(‘Fido‘)>>> e = Dog(‘Buddy‘)>>> d.add_trick(‘roll over‘)>>> e.add_trick(‘play dead‘)>>> d.tricks                # unexpectedly shared by all dogs[‘roll over‘, ‘play dead‘]

Correct design of the class should use an instance variable instead:

class Dog:    def __init__(self, name):        self.name = name        self.tricks = []    # creates a new empty list for each dog    def add_trick(self, trick):        self.tricks.append(trick)>>> d = Dog(‘Fido‘)>>> e = Dog(‘Buddy‘)>>> d.add_trick(‘roll over‘)>>> e.add_trick(‘play dead‘)>>> d.tricks[‘roll over‘]>>> e.tricks[‘play dead‘]