python中self的用法

版权声明: https://blog.csdn.net/qq_41548574/article/details/82761698

self相当于是类对外提供的一个调用属性和动态方法的接口,在类的方法中加上self,则可以通过实例化后的对象调用,没有的话就只能通过类本身调用(类名.函数名())

分为两种情况:

  • 不需要对外提供接口,只能通过类名加方法名调用,代码如下
class Test01():
    
    def __init__(self,t):
        self.t = t
        
    def testfun01(self):
        print("这是第一个测试函数,输出为{0}。".format(self.t))
        
    def testfun02():
        print("这是第二个测试函数。")
        
        
Test01.testfun02()

>>>这是第二个测试函数。

t = Test01()
t.testfun02()
>>>__init__() missing 1 required positional argument: 't'
  • 当需要作为实例化的对象时,要加上self

class Test01():
    
    def __init__(self,t):
        self.t = t
        
    def testfun01(self):
        print("这是第一个测试函数,输出为{0}。".format(self.t))
        
    def testfun02():
        print("这是第二个测试函数。")
        
        

t = Test01("110")
t.testfun01()

>>>这是第一个测试函数,输出为110。

因此,实例化对象应有的功能得方法实现都应该加上self

猜你喜欢

转载自blog.csdn.net/qq_41548574/article/details/82761698
今日推荐