python 대상 코드 예시

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# a class definition
class MyClass:
    """         A Simple Example Class"""
    i = 1234  #       
    def f(self):#      
        return "Hello World"
        
x = MyClass()
print MyClass.__doc__
print x.__doc__

#             
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
        
x = Complex(3.0, -4.5)
print x.r, x.i
x.counter = 2 #instance attribute
print x.counter # print Complex.counter   
del x.counter

#              
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1
    def g(self):
        return 'hello world'
    h = g
#  C.f C.h C.g         

#        ,    self               
class Bag:
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

#       
class BaseClassName:
    pass
  
class DerivedClass(BaseClassName):
    pass
   
class BaseClassName2:
    pass
  
class DerivedClass2(BaseClassName, BaseClassName2):
    pass
  
#    isintance issubclass
d = DerivedClass2()
print isinstance(d, BaseClassName)
print issubclass(DerivedClass2, BaseClassName2)

#    
# python ,            ,                       。
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)
            
#  C        
class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

# python ,              
#     raise Class, instance   raise instance
class B:
    pass
class C(B):
    pass
class D(C):
    pass

for c in [B, C, D]:
    try:
        raise c()
    except D:
        print "D"
    except C:
        print "C"
    except B:
        print "B"

#      
class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
        
rev = Reverse('spam')
for char in rev:
    print char

#   
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]
        
for char in reverse('golf'):
    print char

좋은 웹페이지 즐겨찾기