zoukankan      html  css  js  c++  java
  • 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 spam
    After nonlocal assignment: nonlocal spam
    After global assignment: nonlocal spam
    In 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']


  • 相关阅读:
    margin问题
    IE6里面子集尺寸大的会把父亲撑大
    第一个元素<flout>写了,想在他的旁边加一个元素.IE6会出现缝隙. 不要用margin撑开,要用flout
    兼容性,float
    HTML5的兼容问题以及调用js文件的方法
    表单
    表格的编写,课程表
    SmartThreadPool
    C# 多线程的等待所有线程结束的一个问题
    DataTable保存与读取 stream
  • 原文地址:https://www.cnblogs.com/wintor12/p/3900492.html
Copyright © 2011-2022 走看看