簡體   English   中英

在python中的類之間傳遞屬性

[英]passing attributes between classes in python

盡管閱讀了數小時,但我仍然不知道self和init會做什么。 我最終放棄了嘗試去理解它的作用,而只是知道我需要將其包括在我的代碼中(實際上我什至不確定我是否需要它)。

無論如何,為了學習這些知識,我采用了在某些教程中找到的示例程序,並決定嘗試自己復制它而不參考任何示例。

我可能完全錯了,但是我想做的是有一個按下按鈕以創建新的患者記錄時調用的函數。 我堅持的部分是如何將按鈕按下功能中的那些變量(它們稱為屬性或變量?)傳遞給患者類? 我只是將該函數作為方法放在該類中嗎? 此外,每次按下按鈕后,我還能創建一個新患者嗎?

  def buttonpress():
      name = input("what's your name")
      age = input("what's your age")
      totalpatients +=1


  class patients:
      def __init__(self, name, age):
      self.name = name
      self.age = age

def displaypatient(self):
      print self.age, self.name

firstpatient=patients(name, 16)
firstpatient.displaypatient()

幾周前,我覺得我和你在同一條船上,盡管他們仍然很動搖,但我將盡我所能向你解釋自我和初始化。 其他評論員,請保持溫柔! ;)

我將首先嘗試解釋“自我”,因為它可能使init更加清晰。 當我想上課時,可以通過以下方式進行:

class Car:
    # I can set attributes here ( maybe I want all my cars to have a:
    size = 0
    # well eventually my car object is going to need to do stuff, so I need methods - 
    # methods are like functions but they are only usable by the class that encompasses them!
    # I create them the same way, just inside the indentation of the class, using def func():
    def drive(self):
        print "vroom"
    # pretend this is the function that I would call to make the car drive.

好的。 我們這里只討論一些有關此布局的內容。 我們已經定義了汽車應該做什么,但是我們還沒有做任何事情。 (我保證這是所有相關的!)為了實例化(一次出現)汽車,我們可以將汽車對象分配給新變量:

myCar = car()

現在,我可以使用在汽車類中定義的所有方法-像開車! 我們可以通過鍵入以下內容來調用該函數:

myCar.drive()

這將打印出“ vroom”,我可以通過執行以下操作在同一程序中對car()類進行第二次實例化(盡管這將是一個完全不同的對象):

newCar = car()

現在,開始部分開始了……我做了一個非常簡單的課程,而且課程變得又大又嚇人,幾乎不可能在一夜之內全部理解它們,但現在我將向您解釋自己。

如果我還有其他需要引用該對象的方法,則“ myCar”(我用來保存所創建的汽車對象的變量)將成為“ self”參數。 本質上,如果我需要在該類的ANOTHER方法中引用.vroom(),myCar.vroom()與說self.vroom()相同。

包裹起來,我們看起來像這樣:

class Car:
    size = 0 # a global attribute for all car objects
    def drive(self): #self is the argument!
        print "vroom!"
myCar = car() # we've initialized the class but havent used it here yet!
myCar.drive() # this prints "vroom"

換一種說法,就像在正常函數中一樣,說參數是self只是占位符,無論對象調用該函數是什么。

現在,如果這真棒,那么我將再次對其進行編輯。 def init (self):使用相同的理論,即采用您從類中創建的單個對象,並在每次類創建對象時向其提供指令以執行該操作。

class car:
    def __init__(self): # needs self, to refer to itself, right?
        self.name = name # now we can assign unique variables to each INSTANCE of the car class.

您可以使用def init並對其執行一些瘋狂的操作,例如在其內部,您可以立即調用其他方法和操作。 基本上,這就像在說“嘿,對象! 您還活着,請檢查init函數內部的內容,您需要擁有所有這些東西! 走!

讓我知道這是否有幫助,或者我能否說得更清楚。 就像我說的那樣,我幾乎不會把所有事情都纏住頭,所以也許我的解釋需要一些工作。 干杯:)

您正在嘗試使用基本的面向對象編程,但是需要了解類定義了對象並具有屬性。

在下面的代碼中,我們定義了Patient類:

class Patient:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        return "%s - %s"%(self.age, self.name)

它有一個稱為__init__的方法,該方法由Python定義為從類初始化新對象時調用的方法,並具有幾個參數:

  • 自我-是對我們正在創建的對象的引用,我們將不在這里介紹。 但就目前而言,理解傳遞給對象方法的第一個參數是對自身的引用。
  • 名稱-我們定義的患者姓名
  • 年齡-我們也定義的年齡

第二種方法是一種可以調用該對象的方法,以使它返回我們可能希望將其打印出來的方式。

在下面,我們有創建患者的代碼,並通過顯示方法打印其表示。

firstpatient=patients(name, 16)
print firstpatient.display()

以下是一段代碼,可用於構建一系列患者以便我們在以后的工作中使用。

patients = [] # make an array with nopatients.
def getAnotherPatient():
    name = input("what's your name")
    age = input("what's your age")
    patients.append(Patient(name,age)) # Add a new patient
while somecondition:
    getAnotherPatient()

一旦建立了patients數組中的patients列表,我們就可以遍歷該對象中的對象,然后按照常規操作或顯示它們。

一個基本上由數據(屬性)和用於對該數據進行操作的函數(方法)的集合組成。 類的每個實例都有其自己的數據副本,但共享方法。

因此,一個類的每個*方法都在該類的某個實例上運行,因此該方法需要知道它在哪個實例上進行操作。 這就是self目的self只是表示方法正在使用的實例。

因此,例如:

class House:
    def renovate(self):
        ''' Renovate a house, increasing its value. '''
        self.value += 10000

oldhouse = House() # make a House instance that has no attributes
oldhouse.value = 100000 # set an attribute of the House
mansion = House()
mansion.value = 10000000
oldhouse.renovate() # self will be set to oldhouse, so that oldhouse's value goes up
print oldhouse.value # prints 110000
print mansion.value # prints 10000000: it hasn't changed because renovate knew what it was operating on

現在,在此示例中,請注意我在類外設置了.value 您可以做到這一點(Python允許您在幾乎任何實例上設置任何屬性),但是對每個類都這樣做很麻煩。

這就是__init__出現的地方。這是一種具有特殊含義的方法(因此帶有雙下划線)。 在這種情況下,這是一個在創建類時調用的方法(當您使用Parens調用類以創建新實例時)。 init代表initialization :這是一個初始化類屬性的函數。 創建類時,需要使用任何參數(超出self )。

因此,我們可以將示例更改為:

class House:
    def __init__(self, value):
        self.value = value # set attribute
    def renovate(self):
        ''' Renovate a house, increasing its value. '''
        self.value += 10000

oldhouse = House(100000) # make a House instance with the value set
mansion = House(10000000) # make another House instance with the value set
oldhouse.renovate()
print oldhouse.value # prints 110000
print mansion.value # prints 10000000

並且它的工作原理相同,但會更好一些(因為我們不必繼續在new House上設置.value )。


*除了靜態方法和類方法,以及__new__類的特殊情況

暫無
暫無

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

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