Special method in class

We have seen what class is in the previous sectioin. In the following chapters, we will see several conponents of class.

1. What is special method?

init(self) is a special method. A special method is typically wrapped by two _ on both sides. The special method is actually a common function, yet, will be call by the interpreter instead of you. For example, the init() method will be called by the interpreter when the class is instantiated.

For more examples, when you implement print() function to an object, the**str()** function will be called automatically and return a string which can be used to showed on the screen by print() funciton.

2. Frequently-used special methods.

When we define a class, we always need to use some special methods including

|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| init(self, ...) | The method will be called when a class is instantiated , and it is responsible for initializing some attributes. |
| str(self) | When you implement print(Object) and str(Object) , the method will be called and return a string that you define. |
| repr(self) | When you implement repr(Object) or the Object is in a list which is printed , the method will be called. Then return a string which you define. |
| add(self, ...) | This method is used for operator overload . We can just use**+** operator between numbers before. But if we define the add method, we can use**+operator between our class. |
| getitem(self) | When we use Object[0] or Object[0:2] or for i in Object, the method will be called. |
| len(self) | We can define the length of a class. When
len(Object)** is implemented, the method will be called and return an integral . You can define what is the length of your class. |
| call(self, ...) | We can use the class as a function relying on the method. We will specify it later. |

3. init(self, ...)

We use this method to initialize the class member variables(attributes).

Supposed that we has a class named Car which contains 3 attributes , we can use the init method to initialize the instantiation.

python 复制代码
class Car:
    def __init__(self, speed, weight, height):
        self.speed = speed
        self.weight = weight
        self.height = height

# self.speed is the attribute and defferent from the speed arguments passed from outside.

4. str and repr

The str is the abbrevition of string and typically used to transform your class into a string represtion . The repr is typically used to generate a string prompt of your class.

python 复制代码
class Car:
    def __init__(self, speed, weight, height):
        self.speed = speed
        self.weight = weight
        self.height = height
    
    def __str__(self):
        return f"{self.speed} , {self.weight} , {self.height}"

    def __repr__(self):
        return f"Car({self.speed} , {self.weight} , {self.height})"

# __str__ and __repr__ are very similar.
# __str__ is mainly used by user and __repr__ is mainly used by developer.

5. getitem, if you don't know list, skip this part

You must have used

python 复制代码
a = [1, 2, 3]
print(a[1])

You can exert a for loop on range(0, 3) because the range(0, 3) will return a list.

But you can't exert a for loop like that:

python 复制代码
car1 = Car(10)

print(car[0])

Your class Car cannot be used like because you didn't define the getitem method in you class Car, so the for loop doesn't know where and how to get a list . You must define a getitem method which can return a list and then when the forloop is implemented the car1 will return a list to the for loop.

python 复制代码
class Car:
    def __init__(self, speed):
        self.speed = speed

    def __getitem__(self):
        return [1,2,3]

Then

python 复制代码
car1 = Car(10)
print(car1[0])
print(car1[1])
print(car1[2])

6. add , sub , mul

After you define the 3 method, you can exert + - and * operator on you object car

python 复制代码
class Car:
    def __init__(self, speed):
        self.speed = speed

    def __add__(self, other): #-------------------------> other is another car object
        return Car(self.speed + other.speed)

    def __sub__(self, other): #-------------------------> other is another car object
        return Car(self.speed - other.speed)

    def __mul__(self, other): #-------------------------> other is another car object
        return Car(self.speed * other.speed)

    def __str__(self):    #-----------------------------> remember? we can print the car througth method
        return "speed: {0}".format(self.speed)

Then

python 复制代码
car1 = Car(10)
car2 = Car(20)

print(car1 + car2)
print(car1 - car2)
print(car1 * car2)
相关推荐
跟着珅聪学java几秒前
在 Java 中处理 JSON 去除空 children数组,可以使用 Jackson 库。这里有几种实现方式
开发语言·windows·python
计算机安禾几秒前
【数据结构与算法】第33篇:交换排序(二):快速排序
c语言·开发语言·数据结构·数据库·算法·矩阵·排序算法
William Dawson2 分钟前
Java 后端高频 20 题超详细解析 ①
java·开发语言
lly2024064 分钟前
PHP 魔术常量
开发语言
Evand J5 分钟前
【MATLAB例程分享】三维非线性目标跟踪,观测为:距离+方位角+俯仰角,使用无迹卡尔曼滤波(UKF)与RTS平滑,高精度定位
开发语言·matlab·目标跟踪
编程之升级打怪9 分钟前
Java NIO的简单封装
java·开发语言·nio
wuxinyan12310 分钟前
Java面试题46:一文深入了解JVM 核心知识体系
java·jvm·面试题
小江的记录本13 分钟前
【JEECG Boot】 《JEECG Boot 数据字典使用教程》(完整版)
java·前端·数据库·spring boot·后端·spring·mybatis
Chase_______13 分钟前
【Python基础 | 第5章】面向对象与异常处理:一文搞懂类、对象、封装、继承、多态
开发语言·python
啦啦啦!13 分钟前
项目环境的搭建,项目的初步使用和deepseek的初步认识
开发语言·c++·人工智能·算法