python:関数内のself.variable [閉じる]

python:関数内のself.variable [閉じる]

私はクラスとその機能に焦点を当てたチュートリアルPythonコードを書いています。self.クラス内で定義された変数のメソッドを知りたいです。

self.関数の変数__init__(例関数では0)と以前に定義された変数(同じクラスの他の関数の結果)を使用する他の関数のみを使用する必要がありますか?私の例では、2番目の関数は、次の関数で使用する新しいグローバル変数()を計算するために、および変数をk導入yします。 、 、 、 で定義する必要があります。可変ですか? 2つの違いは何ですか?zckyz__init__

# define the class
class Garage:
    # 0 - define the properties of the object
    # all variables are .self since they are called first time
    def __init__(self, name, value=0, kind='car', color=''):
        self.name = name
        self.kind = kind
        self.color = color
        self.value = value
       
    # 1- print the properties of the object
    # we are calling the variables defined in the previous function
    # so all variables are self.
    def assembly(self):
         desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value) 
         return desc_str
         
    # 2 - calculate coeff of its cost
    # ????
    def get_coeff(self,k=1,y=1,z=1):
        #self.k =k
        #self.y =y
        #self.z =z
        global c
        c=k+y+z
        return c
    # 3  use the coeff to calculate the final cost
    # self.value since it was defined in __init__ 
    # c - since it is global value seen in the module
    def get_cost(self):
        return [self.value * c, self.value * c, self.value * c]
        
car1= Garage('fiat',100)
car1.assembly()

ベストアンサー1

Self はクラスインスタンスの表現なので、オブジェクトプロパティにアクセスしようとすると、コンストラクタは self を使用してインスタンスパラメータにアクセスします。

car1= Garage('fiat',100)
## car1.name = self.name == fiat
## car1.value= self.value == 100

一方、def get_coeff(self,k=1,y=1,z=1)k、y、zがパラメータ(デフォルトは1)である関数があります。これはローカルでのみ使用でき、関数内で変数として操作/オーバーライドでき、コンストラクタに入れることができます。 CLASS の一部であり、機能命令の実行にのみ使用されます。

おすすめ記事