Appearance
Class and Instance
One of the most important concepts in object-oriented programming is the distinction between class and instance. It's essential to remember that a class is an abstract template, such as the Student
class, while an instance is a specific "object" created based on that class. Each object shares the same methods, but their data may differ.
Defining a Class
In Python, you define a class using the class
keyword:
python
class Student(object):
pass
After the class
keyword comes the class name (Student
), which is typically capitalized. Following the class name, (object)
indicates which class the new class inherits from. In most cases, if there isn't a suitable superclass, you use object
, which is the ultimate base class for all classes in Python.
Once the Student
class is defined, you can create instances of that class using the class name followed by parentheses:
python
>>> bart = Student()
>>> bart
<__main__.Student object at 0x10a67a590>
>>> Student
<class '__main__.Student'>
Here, the variable bart
points to an instance of Student
. The memory address (e.g., 0x10a67a590
) is unique for each object, while Student
itself is a class.
Adding Attributes to Instances
You can dynamically bind attributes to an instance. For example, you can add a name
attribute to the bart
instance:
python
>>> bart.name = 'Bart Simpson'
>>> bart.name
'Bart Simpson'
Initializing Attributes with __init__
Classes can serve as templates, and you can enforce the initialization of essential attributes by defining a special method called __init__
. This method allows you to bind attributes like name
and score
when creating an instance:
python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
Note: The special method __init__
is defined with two underscores on both sides. The first parameter of __init__
is always self
, which refers to the instance being created. Thus, inside __init__
, you can bind various attributes to self
.
With the __init__
method, you must provide the parameters required for initialization when creating an instance (excluding self
, which is automatically provided):
python
>>> bart = Student('Bart Simpson', 59)
>>> bart.name
'Bart Simpson'
>>> bart.score
59
Methods in Classes
Methods defined in classes are similar to functions but always have self
as the first parameter. You do not need to pass this parameter when calling the method. For instance, you can define a method to print a student's score:
python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
To call the print_score
method, you use the instance variable:
python
>>> bart.print_score()
Bart Simpson: 59
Data Encapsulation
A crucial feature of object-oriented programming is data encapsulation. In the Student
class, each instance possesses its own name
and score
data. Instead of accessing these attributes through an external function, you can define methods within the class itself, thereby encapsulating the data:
python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
This allows you to access the data through class methods, keeping the implementation details hidden.
Adding New Methods
You can also add new methods to the Student
class, such as a method to get the student's grade:
python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
You can call the get_grade
method on an instance without needing to know the internal implementation details:
python
lisa = Student('Lisa', 99)
bart = Student('Bart', 59)
print(lisa.name, lisa.get_grade())
print(bart.name, bart.get_grade())
Summary
- A class is a template for creating instances, while an instance is a specific object created from that class. Each instance has its own independent data.
- A method is a function that is bound to an instance, allowing it to directly access instance data.
- By calling methods on an instance, you manipulate the object's internal data without needing to know the specifics of the method's implementation.
- Unlike static languages, Python allows you to dynamically bind attributes to instances, meaning two instances of the same class can have different attribute names. For example:
python
>>> bart = Student('Bart Simpson', 59)
>>> lisa = Student('Lisa Simpson', 87)
>>> bart.age = 8
>>> bart.age
8
>>> lisa.age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'