在 Python 中访问类的成员变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3434581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:05:17  来源:igfitidea点击:

Accessing a class' member variables in Python?

pythonclassmethodsreturn

提问by Adam

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

theExample = Example()
print(theExample.itsProblem)

How do I access a class's variable? I've tried adding this definition:

如何访问类的变量?我试过添加这个定义:

def return_itsProblem(self):
    return itsProblem

Yet, that fails also.

然而,这也失败了。

采纳答案by e-satis

The answer, in a few words

答案,几句话

In your example, itsProblemis a local variable.

在您的示例中,itsProblem是一个局部变量。

Your must use selfto set and get instance variables. You can set it in the __init__method. Then your code would be:

您必须使用self来设置和获取实例变量。您可以在__init__方法中设置它。那么你的代码将是:

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


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

但是如果你想要一个真正的类变量,那么直接使用类名:

class Example(object):
    itsProblem = "problem"


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

But be careful with this one, as theExample.itsProblemis automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

但是要小心这个,因为theExample.itsProblem它会自动设置为等于Example.itsProblem,但根本不是同一个变量,可以独立更改。

Some explanations

一些解释

In Python, variables can be created dynamically. Therefore, you can do the following:

在 Python 中,可以动态创建变量。因此,您可以执行以下操作:

class Example(object):
    pass

Example.itsProblem = "problem"

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

print Example.itsProblem == e.itsSecondProblem 

prints

印刷

True

真的

Therefore, that's exactly what you do with the previous examples.

因此,这正是您对前面的示例所做的。

Indeed, in Python we use selfas this, but it's a bit more than that. selfis the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it selfor not.

确实,在 Python 中我们使用selfas this,但不止于此。self是任何对象方法的第一个参数,因为第一个参数始终是对象引用。这是自动的,无论您是否调用它self

Which means you can do:

这意味着您可以:

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


theExample = Example()
print(theExample.itsProblem)

or:

或者:

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


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it selfas a convention.And you add just a variable to this object, the same way you would do it from outside.

完全一样。ANY 对象方法的第一个参数是当前对象,我们只是self作为约定调用它。并且你只向这个对象添加一个变量,就像你从外面做的一样。

Now, about the class variables.

现在,关于类变量。

When you do:

当你这样做时:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

您会注意到我们首先设置了一个类变量,然后我们访问了一个对象(实例)变量。我们从来没有设置这个对象变量,但它有效,这怎么可能?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

好吧,Python 尝试首先获取对象变量,但是如果找不到它,则会为您提供类变量。警告:类变量在实例之间共享,而对象变量不是。

As a conclusion, never use class variables to set default values to object variables. Use __init__for that.

作为结论,永远不要使用类变量为对象变量设置默认值。__init__为此使用。

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

最终,您将了解到 Python 类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再回来阅读。

回答by kennytm

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

您声明的是局部变量,而不是类变量。要设置实例变量(属性),请使用

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

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

To set a class variable(a.k.a. static member), use

要设置类变量(又名静态成员),请使用

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.

回答by andrew pate

If you have an instance function (i.e. one that gets passed self) you can use self to get a reference to the class using self.__class__

如果您有一个实例函数(即一个通过 self 传递的函数),您可以使用 self 来获取对类的引用 self.__class__

For example in the code below tornado creates an instance to handle get requests, but we can get hold of the get_handlerclass and use it to hold a riak client so we do not need to create one for every request.

例如,在下面的代码中,tornado 创建了一个实例来处理 get 请求,但我们可以获取get_handler该类并使用它来保存 riak 客户端,因此我们不需要为每个请求创建一个。

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 ...

回答by mayor

Implement the return statement like the example below! You should be good. I hope it helps someone..

像下面的例子一样实现 return 语句!你应该很好。我希望它可以帮助某人..

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


theExample = Example()
print theExample.the_example()