zoukankan      html  css  js  c++  java
  • python中的self

    1、首先明确的是self只有在类的方法中才会有,独立的函数或方法是不必带有self的。self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

    self名称不是必须的,在python中self不是关键词,你可以定义成a或b或其它名字都可以,但是约定成俗,不要搞另类,大家会不明白的。下例中将self改为myname一样没有错误:

    1 class Person:
    2 def _init_(myname,name):
    3 myname.name=name
    4 def sayhello(myname):
    5 print 'My name is:',myname.name
    6 p=Person('Bill')
    7 print p

    self指的是类实例对象本身(注意:不是类本身)。

    1 class Person:
    2 def _init_(self,name):
    3 self.name=name
    4 def sayhello(self):
    5 print 'My name is:',self.name
    6 p=Person('Bill')
    7 print p

    在上述例子中,self指向Person的实例p。 为什么不是指向类本身呢,如下例子:

    1 class Person:
    2 def _init_(self,name):
    3 self.name=name
    4 def sayhello(self):
    5 print 'My name is:',self.name
    6 p=Person('Bill')
    7 p1 = Person('Apple')
    8 print p

    如果self指向类本身,那么当有多个实例对象时,self指向哪一个呢?

    2、普通的方法,第一个参数需要是self,它表示一个具体的实例本身。
    如果用了staticmethod,那么就可以无视这个self,而将这个方法当成一个普通的函数使用。
    而对于classmethod,它的第一个参数不是self,是cls,它表示这个类本身。
    >>> class A(object):
        def foo1(self):
            print "Hello",self
        @staticmethod
        def foo2():
            print "hello"
        @classmethod
        def foo3(cls):
            print "hello",cls

  • 相关阅读:
    python中selenium+unittest实操
    python+selenium元素定位04——浏览器多窗口处理
    python+selenium元素定位03——自动化常见场景处理
    python+selenium元素定位02——层级定位
    requests.post() 方法的使用
    python+selenium元素定位01——显式、隐式等待
    python+selenium之元素识别二
    IO流常用基类
    STS中导入Jmeter源码遇到的坑
    MySql处理日期时间常用函数
  • 原文地址:https://www.cnblogs.com/work115/p/5588686.html
Copyright © 2011-2022 走看看