Created
December 13, 2011 14:53
-
-
Save dketov/1472401 to your computer and use it in GitHub Desktop.
Методы классов
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment