96
class Example(object):
    def the_example(self):
        itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

クラスの変数にアクセスするにはどうすればよいですか?私はこの定義を追加しようとしました:

def return_itsProblem(self):
    return itsProblem

しかし、それも失敗します。

4

5 に答える 5

170

答えは、一言で言えば

あなたの例でitsProblemは、はローカル変数です。

selfインスタンス変数を設定および取得するには、を使用する必要があります。メソッドで設定できます__init__。その場合、コードは次のようになります。

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

ただし、真のクラス変数が必要な場合は、クラス名を直接使用してください。

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

ただし、これtheExample.itsProblemは自動的にに等しく設定されるため注意してExample.itsProblemください。ただし、まったく同じ変数ではなく、個別に変更できます。

いくつかの説明

Pythonでは、変数を動的に作成できます。したがって、次のことができます。

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

プリント

したがって、これは前の例で行ったこととまったく同じです。

確かに、Pythonではとしてを使用selfしますthisが、それよりも少し多くなります。self最初の引数は常にオブジェクト参照であるため、は任意のオブジェクトメソッドの最初の引数です。これは、呼び出すかどうかに関係なく、自動的に行われselfます。

つまり、次のことができます。

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

また:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

まったく同じです。ANYオブジェクトメソッドの最初の引数は現在のオブジェクトでありself、慣例としてのみ呼び出します。そして、外部から行うのと同じ方法で、このオブジェクトに変数だけを追加します。

さて、クラス変数について。

あなたがするとき:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

最初にクラス変数を設定し、次にオブジェクト(インスタンス)変数にアクセスします。このオブジェクト変数を設定することはありませんが、機能します。どうすればそれが可能ですか?

さて、Pythonは最初にオブジェクト変数を取得しようとしますが、それが見つからない場合は、クラス変数を提供します。警告:クラス変数はインスタンス間で共有されますが、オブジェクト変数は共有されません。

結論として、クラス変数を使用してデフォルト値をオブジェクト変数に設定しないでください。そのために使用__init__します。

最終的には、Pythonクラスがインスタンスであり、したがってオブジェクト自体であることがわかります。これにより、上記を理解するための新しい洞察が得られます。気づいたら、戻って後でもう一度読んでください。

于 2010-08-08T14:05:50.750 に答える
13

クラス変数ではなく、ローカル変数を宣言しています。インスタンス変数(属性)を設定するには、

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

クラス変数(別名静的メンバー)を設定するには、次を使用します。

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.
于 2010-08-08T14:04:05.070 に答える
8

インスタンス関数(つまり、selfを渡される関数)がある場合は、selfを使用して、を使用してクラスへの参照を取得できます。self.__class__

たとえば、以下のコードでは、tornadoはgetリクエストを処理するインスタンスを作成しますが、get_handlerクラスを取得してそれを使用してriakクライアントを保持できるため、リクエストごとに1つ作成する必要はありません。

import tornado.web
import riak

class get_handler(tornado.web.requestHandler):
    riak_client = None

    def post(self):
        cls = self.__class__
        if cls.riak_client is None:
            cls.riak_client = riak.RiakClient(pb_port=8087, protocol='pbc')
        # Additional code to send response to the request ...
    
于 2016-10-27T16:41:05.220 に答える
0

以下の例のようにreturnステートメントを実装してください!あなたは良いはずです。私はそれが誰かを助けることを願っています。

class Example(object):
    def the_example(self):
        itsProblem = "problem"
        return itsProblem 


theExample = Example()
print theExample.the_example()
于 2017-05-24T14:46:29.090 に答える
0

@classmethod静的メソッドがある場合は、常に最初のパラメーターとしてクラスがあります。

class Example(object):
    itsProblem = "problem"

    @classmethod
    def printProblem(cls):
        print(cls.itsProblem)

Example.printProblem()
于 2022-01-14T09:45:58.663 に答える