簡體   English   中英

在python腳本中正確使用'self'

[英]proper using of 'self' in a python script

我終於要創建一個類,以更簡化的方式分析數據。 它獲取一個CSV文件,並輸出有關表及其列的一些信息。

class Analyses:
    def Types_des_colonnes(self, df):
        tcol = df.columns.to_series().groupby(df.dtypes).groups
        tycol = {k.name: v for k, v in tcol.items()}
        return(self.tycol)

    def Analyse_table(self, table):
        # Renvoi un dico 'tycol' avec les types en clef et les noms des colonnes en valeur:
        Types_des_colonnes(table)
        nbr_types_colonnes_diff=len(tycol.keys())


        type_table = table.dtypes
        liste_columns = table.columns
        clef_types= tycol.keys()
        long_table = len(table)
        nbr_cols = len(liste_columns)

        print(table.describe())

        print('Nombre de colonnes: '+ str(nbr_cols))
        print('Nombre de types de colonnes différentes: '+str(nbr_types_colonnes_diff))
        for kk in range(0,nbr_types_colonnes_diff):
            print('Type: ' + tycol.keys()[kk])
            print(tycol.values())
        return(liste_columns)

    def Analyse_colonne(self, col):
        from numpy import where, nan
        from pandas import isnull,core,DataFrame
        # Si col est un dataframe:
        if type(col) == core.frame.DataFrame:
            dict_col = {}
            for co in col.columns:
                dict_col_Loc = Analyse_colonne(col[co]);
                dict_col[co] = dict_col_Loc.values()
            return(dict_col)
        elif type(col) == core.series.Series:    
            type_col = type(col)
            arr_null = where(isnull(col))[0]
            type_data = col.dtype
            col_uniq = col.unique()

            nbr_unique= len(col_uniq)
            taille_col= len(col)
            nbr_ligne_vide= len(arr_null)

            top_entree= col.head()
            bottom_entree= col.tail()
            pct_uniq= (float(nbr_unique)/float(taille_col))*100.0
            pct_ligne_vide= (float(nbr_ligne_vide)/float(taille_col))*100.0
            print('\n')
            print('       #################      '+col.name+'      #################')
            print('Type des données: ' + str(type_data))
            print('Taille de la colonne: ' + str(taille_col))
            if nbr_unique == 1:
                print('Aucune entrée unique')
            else:
                print('Nombre d\'uniques: '+ str(nbr_unique))
                print('Pourcentage d\'uniques: '+str(pct_uniq)+' %')
            if nbr_ligne_vide == 0:
                print('Aucune ligne vide')
            else:
                print('Nombre de lignes vides: '+ str(nbr_ligne_vide))
                print('Pourcentage de lignes vides: '+str(pct_ligne_vide)+' %')

            dict_col = {}
            dict_col[col.name] = arr_null
            return(dict_col)
        else:
            print('Problem')

def main():
    anly = Analyses()
    anly.Analyse_table(df_AIS)

if __name__ == '__main__':
    main()

運行此腳本時,我得到:

NameError: name 'tycol' is not defined

指的是第二行:

def Analyse_table():
        # Renvoi un dico 'tycol' avec les types en clef et les noms des colonnes en valeur:
        Types_des_colonnes(table)
        nbr_types_colonnes_diff=len(tycol.keys())

我知道這與正確使用“自我”有關,但我真的不明白如何正確使用“自我”。 誰能告訴我如何解決這個非常簡單的問題?

(我添加了此腳本中存在的所有“自我”,只是試圖使它自己運行。)

Python對象的成員通過位於的右側與其他變量區分開. (與obj.member

方法的第一個參數綁定到在其上調用該方法的對象。 按照慣例,此參數稱為self ,這不是技術要求。

tycol是一個正常的變量,用完全非關聯Analyses對象。 self.tycol是一個不同的名稱。

請注意,如何從Types_des_colonnes return self.tycol而不給它任何值(這應該引發AttributeError 。您是否嘗試過將代碼發布到問題正文中時運行代碼?)。 然后,您可以在呼叫站點放棄該值。

您應該的結果分配Types_des_colonnes一個名字在Analyse_table ,或只使用名稱self.tycol

def Types_des_colonnes(self, df):
    tcol = df.columns.to_series().groupby(df.dtypes).groups
        # we don't care about tcol after this, it ceases to exist when the method ends
    self.tycol = {k.name: v for k, v in tcol.items()}
        # but we do care about self.tycol

def Analyse_table(self, table):
    # Renvoi un dico 'tycol' avec les types en clef et les noms des colonnes en valeur:
    Types_des_colonnes(table)
    nbr_types_colonnes_diff = len(self.tycol.keys())
    # ...

Types_de_colonnes方法中,您需要做: self.tycol=tycol 另外,您需要將方法稱為“作為方法”。 花一個星期閱讀一本有關python的書,以學習一些基礎知識。 編程很容易,但並不容易:)

類是包含“數據和對該數據進行操作的方法”的數據結構。 請注意,我之所以沒有說“函數”,是因為一個類始終可以訪問該類中包含的數據,因此從數學意義上講,該類中的方法不是“函數”。 但是,也許是另一天。

那么,您何時使用self self表示您要在其中調用方法的類的實際實例。 因此,如果您有一個名為Shape的類以及Shape ab兩個實例,則在調用a.area()area方法內的self對象將引用名為aShape實例,在調用b.area() self對象是Shapeb實例

這樣,您可以編寫適用於Shape任何實例的方法。 為了更加具體,這是一個Shape類示例:

class Shape():
    def __init__(self, length_in, height_in):
        self.length = length_in
        self.height = height_in

    def area(self):
        return self.length * self.height

在這里,您可以看到Shape類中包含的數據是長度和高度。 這些值在__init__ (在構造函數中,即Shape a(3.0,4.0) )處分配,並作為self成員分配。 然后,可以通過self對象通過方法area訪問后記,以進行計算。 也可以重新分配這些成員,並可以創建新成員。 (盡管通常只在構造函數中創建成員)。

與Python設計的其他簡單方面相比,這一切都很奇怪。 但是,這並不是Python獨有的。 在C ++中,有一個this指針,其作用相同,在JavaScript中,閉包用於創建對象的方式通常使用this變量來執行與Python的self相同的任務。

希望這會有幫助。 我可以談談您還有其他任何問題。

同樣,在文件頂部進行import語句通常也是一個好主意。 有一些原因,但沒有一個足以讓普通編碼人員使用。

暫無
暫無

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

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