python面向对象-self

概述

self 关键字 用于 __init__() 、成员方法 等方法中,表示当前对象

关于 “自己” 的理解

李雷说:“自己”,“自己” 表示李雷

韩梅梅说:“自己”,“自己” 表示韩梅梅

每个人说的 “自己”,都表示说话人自己

关于 self 的理解

self 相当于 “自己”,表示当前对象

注意

不能在 静态方法 中使用

例子

class Phone:

    def __init__(self,name):
        print("self:",self)
        self.name = name



huawei = Phone("华为mate40")
print("huawei:",huawei) # 该对象的内存地址


iphone14 = Phone("iphone14暗夜黑")
print("iphone14:",iphone14) # 该对象的内存地址

例子2

class Phone:

    def __init__(self,name):
        self.name = name

    def call(self,num):
        print("call self:",self)
        print("用",self.name,"打电话给",num)

huawei = Phone("华为mate40")
print("huawei:",huawei) # 该对象的内存地址
huawei.call("110")

iphone14 = Phone("iphone14暗夜黑")
print("iphone14:",iphone14) # 该对象的内存地址
iphone14.call("120")


原文出处:https://malaoshi.top/show_1IX5StSHF7Xw.html