Python - 面向对象编程 - self 参数

时间:2021-08-30 13:34:55   收藏:0   阅读:5

为什么要讲 self 参数

class PoloBlog:
    def __init__(self):
        ...

    def say(self):
        ...

 在类里面,所有实例方法都需要加 self 参数,且排在第一个,有且仅有一个

 

self 参数的含义

在类中定义的方法,第一个参数 self 指向调用该方法的实例对象,在方法中通过  self.属性 这样的形式访问对象的实例属性

 

self 参数真的必须叫 self 吗

class test:
    def __init__(polo):
        polo.name = "小菠萝"

    def test(polo):
        print(polo.name)


t = test()
t.test()


# 输出结果
小菠萝

只是可读性很差

 

如何理解 self 参数 

类比

 

重点

 

通过代码了解 self

# self
class PoloBlog:
    def __init__(self):
        print("构造方法:self is ", self, " self 的 id is ", id(self))

    def say(self):
        print("实例方法:self is ", self, " self 的 id is ", id(self))


# 实例对象一
blog1 = PoloBlog()
blog1.say()
print("实例对象 blog1 id is ", id(blog1))

# 实例对象2
blog2 = PoloBlog()
blog2.say()
print("实例对象 blog2 id is ", id(blog2))


# 输出结果
构造方法:self is  <__main__.PoloBlog object at 0x10f884af0>  self 的 id is  4555557616
实例方法:self is  <__main__.PoloBlog object at 0x10f884af0>  self 的 id is  4555557616
实例对象 blog1 id is  4555557616

构造方法:self is  <__main__.PoloBlog object at 0x10f884ac0>  self 的 id is  4555557568
实例方法:self is  <__main__.PoloBlog object at 0x10f884ac0>  self 的 id is  4555557568
实例对象 blog2 id is  4555557568

 

原文:https://www.cnblogs.com/poloyy/p/15190295.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!