RUVIDEO
Поделитесь видео 🙏

Intermediate Python 24. __str__ and __repr__ 영어 파이썬 코딩영어

📁 Обучение 👁️ 16 📅 03.12.2023

__str__은 일반인들도 보고 독해가 가능한 형식으로 글구, __repr__는 프로그래머가 디버깅 목적으로 자기나 자기 그룹만 알아볼 수 있게 가능한 압축해서 로그를 기록해내게 하는 기능.

LC training(3:49) - Now what i'm gong to go ahead and do is head on over to the actual blob dot py So this is the that what we're actually importing this is our blob class the base class anyways They are the parent class We are modifying that up here with the blue blobs and the red blobs and the green blob But we don't have to give each of these their own repr method We actually just need we could just do it in this parent class here So what i'll do is just come down here and now i'm going to go ahead and do a dunder repr and we just need to pass self we do need the other dunder though and now we're gonna do is just obviously it just returns a string right And like we were saying the repr method's really more kind of for debugging purposes It should be as condensed as possible We're not really it's not really meant to be output to a console in production use It's just really for debugging ... So now we have repr method Let's save that let's pop on over to blob world Looks good And now let's print blue blobs zero and now at least we have something a little more useful We've got the color again this is an RGB the size and then the x y coordinates location

Code results -

import random
class Blob:
def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-7,7)):
self.size = random.randrange(size_range[0], size_range[1])
self.color = color
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.movement_range = movement_range

def __repr__(self):
return 'Blob({}, {}, ({}, {}))'.format(self.color,
self.size,
self.x,
self.y)

def __str__(self):
return "Color: {} blobject of size {}. Located at {},{}".format(self.color,
self.size,
self.x,
self.y)

class BlueBlob(Blob):
def __init__(self, x_boundary, y_boundary):
Blob.__init__(self, (0, 0, 255), x_boundary, y_boundary)
def __add__(self, other_blob):
logging.info('Blob add op {} + {}'.format(str(self), str(other_blob)))
if other_blob.color == (255, 0, 0):
self.size -= other_blob.size
other_blob.size -= self.size
elif other_blob.color == (0, 255, 0):
self.size += other_blob.size
other_blob.size = 0
elif other_blob.color == (0, 0, 255):
pass
else:
raise Exception('Tried to combine one or multiple blobs of unsupported colors.')

if __name__ == '__main__':
blue_blobs = dict(enumerate([BlueBlob(WIDTH,HEIGHT) for i in range(STARTING_BLUE_BLOBS)]))
red_blobs = dict(enumerate([RedBlob(WIDTH,HEIGHT) for i in range(STARTING_RED_BLOBS)]))
green_blobs = dict(enumerate([GreenBlob(WIDTH,HEIGHT) for i in range(STARTING_GREEN_BLOBS)]))
pygame.quit()
#main()


원본 비디오: https://www.youtube.com/watch?v=vOqrMPcF7xQ&list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&index=25&t=1s

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Intermediate Python 24. __str__ and __repr__ 영어 파이썬 코딩영어», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.