• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Classes and Objects in Python

October 22, 2021 Python

In this post, you will learn how to work with classes and objects so that you can use that same knowledge and thus evolve.

  • a class represents a set of objects, and defines their behavior through methods and which states it is able to maintain through its attributes;
  • an object is an instance of a class and is capable of storing states through its attributes and reacting to messages sent to it.
class Enemy:
   lives = 5

   def attack(self):
     print('I was attacked and lost a live.')
     self.lives -= 1

   def check Life(self):
     if self.lives <= 0:
       print('I\'m dead because I don\'t have any more lives.')
     else:
       print('I\'m still in combat and have', self.lives, 'lives.')

enemy1 = Enemy()
enemy2 = enemy()

enemy1.attack() # I was attacked and lost a live.
enemy1.attack() # I was attacked and lost a live.
enemy1.attack() # I was attacked and lost a live.
enemy1.checkLife() # I'm still in combat and have 2 lives.
enemy2.checkLife() # I'm still in combat and have 5 lives.

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved