class PoloBlog: def __init__(self): ... def say(self): ...
在类里面,所有实例方法都需要加 self 参数,且排在第一个,有且仅有一个
在类中定义的方法,第一个参数 self 指向调用该方法的实例对象,在方法中通过 self.属性 这样的形式访问对象的实例属性
class test: def __init__(polo): polo.name = "小菠萝" def test(polo): print(polo.name) t = test() t.test() # 输出结果 小菠萝
只是可读性很差
# 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