簡體   English   中英

如何在python中的不同文件中使用一個類的方法到另一個類

[英]How to use method of one class to another class in different files in python

我對python很陌生,所以請原諒我的基本問題。 過去幾天我嘗試了谷歌,但無法在我的程序中使用。

任何人都可以向我展示一個很好的例子,我如何在 python 中使用從一個類到另一個類的方法,以及__init__在定義類時的意義。

我正在使用 python2.7

感謝期待。

要在另一個類中使用一個類中定義的方法,您有多種選擇:

  1. 從 A 的方法之一中創建 B 的實例,然后調用 B 的方法:

     class A: def methodInA(): b = B() b.methodInB()
  2. 如果合適,使用繼承的概念(面向對象設計的定義概念之一)來創建您希望使用其方法的原始類的子類:

     class B(A): ...

__init__()是一個類初始化器 每當您實例化一個對象時,您都會調用__init__()無論它是否明確定義。 它的主要目的是初始化類數據成員:

class C:
    def __init__(self, name):
        self.name = name
    def printName(self):
        print self.name

c = C("George")
c.printName() # outputs George

定義__init__() ,特別是在本示例中使用附加參數name ,您可以通過允許實例之間的不同初始狀態來區分可能被通用構造的實例。

這里有2個問題:

第一:在B類中使用A類的方法,兩個類在不同的文件中

class A:
    def methodOfA(self):
        print "method Of A"

讓上面的類在文件 a.py 中 現在 B 類應該在 b.py 中。 假定 a.py 和 b.py 處於同一級別或同一位置。 然后 b.py 看起來像:

import a
class B:
    def methodOfB(self):
        print "Method of B"
        a.A().methodOfA()

你也可以通過在 B 中繼承 A 來做到這一點

import a
class B(a.A):
    def methodOfB(self):
        print "Method of B"
        self.methodOfA()

在 B 中使用 A 的方法還有其他幾種。我將留給您探索。

現在回答你的第二個問題。 __init__在類中的使用。 __init__不是構造函數,正如上面普遍認為和解釋的那樣。 顧名思義,它是一個初始化函數。 它只有在對象已經被構造之后才會被調用,並且它被隱式地傳遞給對象實例作為第一個參數,正如其參數列表中的self所表示的那樣。

python 中的實際構造函數稱為__new__ ,它不需要對象來調用它。 這實際上是一個專門的靜態方法,它接收類實例作為第一個參數。 __new__僅在類從 python 的對象基類繼承時才公開用於覆蓋

在創建類的對象時傳遞任何其他參數,首先轉到__new__ ,然后將對象實例傳遞給__init__ ,如果它接受它們。

init函數就是所謂的構造函數。 創建類object = myClass()的實例時, init是自動調用的函數。 IE

話雖如此,要將函數從一個類調用到另一個類,您需要在第一個類中調用第二個類的實例,反之亦然。 例如。

class One():
    def func(self):
        #does sometthing here

class Two():
    def __init__(self):
        self.anotherClass = One()
        #Now you can access the functions of the first class by using anotherClass followed by dot operator
        self.anotherClass.func()

#When you call the main class. This is the time the __init__ function is automatically called

mainClass = Two()

從另一個類訪問的另一種方法是使用稱為繼承的oop概念。

class One():
    def __init__(self):
        print('Class One Called')
    def func(self):
        print('func1 Called')

class Two(One):
    def __init__(self):
        One.__init__(self,) #This basically creates One's instance
        print('Main Called')

c= Two()
c.func()

這個輸出是:

一級叫
主要調用
func1 調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM