1. 程式人生 > >類的內建方法__

類的內建方法__

__具有唯一性,不同類下面得相同__函式名字,是不同的,這個是有自己的作用域的,當你繼承父類的時候,是不可以呼叫父類裡面的這個方法的,

繼承:當子類沒有這個方法或者屬性的時候,就去父類裡面找,__函式名字

 

繼承的用法:
例子1
class A():
  def __edit(self):
    print('A的edit方法')
    return 'A的edit'
class B(A):
  print('B')
  def __edit(self):
    print('B的edit方法')
    return 'B的edut'

##第一種呼叫的方法
    obj=B().__edit()


    print(obj)
##執行報錯,調用不了父類的__的方法(內建的方法)報錯

 


講解:
這個__edit在這個類下面是有自己的作用域的,外部是調用不了的

例子2:在自己的作用域下面盡進行呼叫這個類下面內建的方法(特殊)

class A():
  def __edit(self):
    print('A的edit方法')
    return 'A的edit'
class B(A):
  print('B')
  def __edit(self):
    print('B的edit方法')
    return 'B的edut'

  def fun(self):


    a=self.__edit()
    # print(a)
    return a

##通過呼叫B下面的fun方法來呼叫__edit
    obj=B().fun()
    print(obj)

##通過init來呼叫這個內建的方法
class B(A):
  print('B')
  def __init__(self):
    self.__edit()
##第二種
    # a=self.fun()
    # print(a)
  def __edit(self):
    print('B的edit方法')
    return 'B的edut'

  def fun(self):


    a=self.__edit()
    # print(a)
    return a
B()

 

例子3:
繼承呼叫父類的方法:(不是內建的方法)
class A():

def __init__(self):
self.__edit()
  def __edit(self):
    print('A的edit方法')
    return 'A的edit'

  def fun2(self):
    print('A的fun2')
class B(A):
  print('B')
  def __init__(self):
    self.fun2()

  # def __edit(self):
    # print('B的edit方法')
    # return 'B的edut'

  def fun(self):
    a=self.__edit()
    # print(a)
    return a
B()

 

##繼承呼叫父類的:(__edit作用域在父類那裡,子類不能呼叫)
報錯
class A():

  def __init__(self):
    self.__edit()
  def __edit(self):
    print('A的edit方法')
    return 'A的edit'

  def fun2(self):
    print('A的fun2')
class B(A):
  print('B')
  def __init__(self):
    self.__edit()

    # def __edit(self):
    # print('B的edit方法')
    # return 'B的edut'

  def fun(self):
    a=self.__edit()
    # print(a)
    return a
B()