Lesson explanation
After this lesson, you will be able to:
self.If you have used classes in Java or C#, Python's basic idea will be familiar: a class defines a type of object, and an instance is one particular object of that class. Python uses a colon and indentation rather than braces:
class Server:
passFor now, pass gives the class a valid, empty body. Create an object by calling the class name: server = Server(). You can attach fields, called attributes, directly to that instance with dot notation: server.region = "eu". Two instances can hold different values without affecting each other.
A method is a function written inside a class. An instance method declares self as its first parameter. When you call server.label(), Python passes server as self automatically. Inside the method, self.region means the region of the particular object receiving the call. Methods can also update instance attributes.
For this first lesson, we assign attributes after creating each object so that you can see the object model clearly. In the next lesson, __init__ will show how to initialize attributes when an object is created. We will cover class attributes and inheritance later.
An empty class is enough to create instances and attach different values to each one.
class Endpoint:
pass
public = Endpoint()
public.path = "/public"
internal = Endpoint()
internal.path = "/internal"
print(public.path)
print(internal.path)Output:
/public
/internalThe two path attributes belong to different objects.
The same method can return a different result for each instance because self refers to the object that called it.
class Printer:
def label(self):
return f"{self.name} ({self.region})"
first = Printer()
first.name = "labels"
first.region = "eu"
print(first.label())Output:
labels (eu)The method uses the attributes attached to first.
A method can change an attribute through self. This change stays with that object.
class Counter:
def record(self):
self.total += 1
counter = Counter()
counter.total = 0
counter.record()
counter.record()
print(f"Total: {counter.total}")Output:
Total: 2The total attribute was created before record() used it. The next lesson will make that setup more reliable.
| Goal | Python |
|---|---|
| Define a class | class Worker: |
| Keep an empty body valid | pass |
| Create an instance | worker = Worker() |
| Assign an instance attribute | worker.name = "api" |
| Read an attribute | worker.name |
| Define an instance method | def label(self): |
| Use the calling object inside a method | self.name |
self in a method: normal instance methods need it as their first parameter.self.name, not just name, to read that instance's attribute.first.status does not change second.status.AttributeError.