Skip to content

Instantly share code, notes, and snippets.

@jigi-33
Created May 25, 2020 14:24
Show Gist options
  • Save jigi-33/034c09d9352ab632a6084cefc6e19069 to your computer and use it in GitHub Desktop.
Save jigi-33/034c09d9352ab632a6084cefc6e19069 to your computer and use it in GitHub Desktop.
Классы дескрипторы, отличие дэндр методов __new__ и __init__
"""
КЛАССЫ И МЕТАКЛАССЫ.
МЕТОДЫ __new__ и __init__
"""
# ВОПРОС:
# Для чего используются, какие аргументы получают, что должны возвращать методы __new__, __init__
# __new__ - принимает объект класса, возвращает его экземпляр. Пример:
q = Q.__new__(Q)
# __init__ - принимает экземпляр и значения аттрибутов класса. Ничего не возвращает. Это инифиализатор класса.
Q.__init__(q, *args, **kwargs)
# Классы-дескрипторы, классифицирующие тип аттрибута:
import abc
class Property:
__counter = 0
def __init__(self, value):
self.__type = type(value)
self.__attr = '{}#{}'.format(self.__class__.__name__, self.__counter)
self.__value = value
Property.__counter += 1
def __set__(self, instance, value):
if type(value) == self.__type:
instance.__dict__[self.__attr] = value
else:
raise TypeError ('Value must be: {}'.format(self.__type))
def __get__(self, instance, objtype=None):
try:
return instance.__dict__[self.__attr]
except KeyError:
return self
class Image(object):
height = Property(0)
width = Property(0)
path = Property('/tmp/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment