dketov
12/13/2011 - 2:53 PM

Методы классов

Методы классов

# -*- encoding: utf-8 -*-
"""
Перегрузка оператора ()
"""

import time

class Logger:
    def __init__(self, filename):
        self.filename = filename
    def __call__(self, string):
        file = open(self.filename, 'a')
        file.write('[' + time.asctime() + '] ')
        file.write(string + '\n')
        file.close()

log = Logger('logfile.txt')

log('Starting program')

log('Trying to divide 1 by 0')

print 1 / 0

log('The division succeeded')

log('Ending program')
# -*- encoding: utf-8 -*-
"""
Метод, определённый вне класса
"""

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

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

a = C
a.g
# -*- encoding: utf-8 -*-
"""
Метод, определённый внутри класса
"""

class NextClass:                            # define class
    def printer(self, text):                # define method
        self.message = text                 # change instance
        print self.message                  # access instance

x = NextClass()                             # make instance

x.printer('instance call')                  # call its method

print x.message                             # instance changed

NextClass.printer(x, 'class call')          # direct class call

print x.message                             # instance changed again