Objects are nouns that can be described with adjectives (attributes) and can do things with verbs (methods).
Classes are the blueprints for objects.
Instance – The result of using, or calling, a class.
Method – A function defined inside of a class.
Attribute – A variable that belongs to a class.
Classes
You call a class like you call a function.
warrior = Character()
Except, a class doesn’t run, it creates an instance of a class.
Attributes
Using attributes
class Thief:
sneaky = True
Testing Attributes
>>> from characters import Thief
>>> kenneth = Theif( )
>>> kenneth.sneaky
True
>>> kenneth.sneaky = False
>>> kenneth.sneaky
False
>>> Thief.sneaky
True
Methods
Methods are functions that’s belong to a class.
Whenever they’re used, however, they’re used by an instance, not by the actual class.
Because of that, methods always take at least one parameter, which represents the instance that’s using the method. By convention that parameter’s always called self
.
import random
class Thief:
sneaky = True
def pickpocket(self):
print("Called by {}".format(self))
return bool(random.randint(0,1))
Calling a Method
You call a method using the instance: kenneth.pickpocket()
import random
class Thief:
sneaky = True
def pickpocket(self):
if self.sneaky:
return bool(random.randint(0,1))
return False
Why We Must Use self
Inside Methods
Calling an instance method as kenneth.pickpocket()
is actually calling the method using the class and passing the instance into it as an argument, like so: Thief.pickpocket(kenneth)
.
Why do that?
Well, unlike some other languages, when a new object is created in Python , it does not create a new set of instance methods for itself. Instance methods in Python lie within the class object without being created with each object initialization — a nice way to save up memory. Recall that Python is a fully object oriented language and so a class is also an object. So it lives within the memory. Class attributes used inside of a method also must be preceded by self
for the same reason obviously.