Week 6 - Classes and object-oriented programming
Week 6 - Classes and object-oriented programming#
Learn the basics of object-oriented programming in Python using classes
Work with tiled images
Week 6a - Classes#
Object-oriented Programming - 1#
… So when you have a list
l, and you call ‘l.append()
,append` is actually a method.
What is the difference between a function and a method?
What is one of the added values of object-oriented programming?
Which keyword do we use to define new datatypes?
… and this one you never call directly either (
__str__) … These methods get called behind your back by Python.
What does behind your back mean in this context?
… I haven’t talked about how I would use this class, and this is one of the beauties of object-oriented programming. I can define this class without worrying about how other people are going to use it.
How does object-oriented programming help in this context?
Object-oriented Programming - 2#
Scott defines three classes:
CircularDomainWe see later that we only have to change the field that the ball is bouncing in to create another behavior in our program — in other words we do not have to change the
How is this achieved?
Working with Objects#
How can we get the datatype of the object that a (variable) name is pointing to?
How do we create an object of a datatype that we created?
Joe uses the
Particle.move()method on a particle tuple by executing
p.move()and gets an
AttributeError. What is the problem?
Classes for Blackjack#
Scott defines three classes for Blackjack
Cardhas rank & suit (for drawing a card’s image)
Handis a collection of cards (we can
hit(), we can get the
Deckis a collection of cards (we can
Joe mentioned that Scott did not like his class design approach, because Joe had included a value attribute in
Card. Why is this a problem in context of object-oriented programming?
How I implemented a deck – well, it’s not so important as long as I have a correct class (implementation that you can work with)…
What is the advantage of object-oriented programming that Joe mentions?
Week 6b - Tiled Images#
How can we calculate the center of the card which is on the second row and sixth column?
♣️ Club Suit
♠️ Spade Suit
♥️ Heart Suit
♦️ Diamond Suit Ranks:
2 to 10
You want to draw a single image from a tiled image and you did not look at the image. How can you calculate the center of an image?
You can also upload your images on other platforms like https://imgur.com
… when objects share state, when you change one object you can change the other This is typically not what you want. This happens for example, when we initialize the object using a mutable object like a
listand we assign the list directly to a class attribute (attribute is a name associated with an object like function and class).
What would you do to avoid this problem?
Programming Tips - 6#
You do not have to include the
__init__. It returns implicitly the created object.
TimeLimitErrorin CodeSkulptor mean?