如何设置和访问类的属性?

发布于 2024-09-13 08:41:31 字数 504 浏览 6 评论 0原文

假设我有这段代码:

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

theExample = Example()
print(theExample.itsProblem)

当我尝试它时,我收到一条错误消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no attribute 'itsProblem'

如何访问此属性?我尝试添加另一种方法来返回它:

    def return_itsProblem(self):
        return itsProblem

但问题仍然存在。

Suppose I have this code:

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

theExample = Example()
print(theExample.itsProblem)

When I try it, I get an error that says:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no attribute 'itsProblem'

How do I access this attribute? I tried adding another method to return it:

    def return_itsProblem(self):
        return itsProblem

but the problem persists.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

季末如歌 2024-09-20 08:41:31

答案,简而言之

在您的示例中,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 类是实例,因此也是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再回来阅读这篇文章。

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

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.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

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

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 self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

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 self as a convention. And you add just a variable to this object, the same way you would do it from outside.

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.

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

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.

黑白记忆 2024-09-20 08:41:31

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

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.

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.
负佳期 2024-09-20 08:41:31

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

例如,在下面的代码中,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 ...
    

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__

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

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 ...
    
狂之美人 2024-09-20 08:41:31

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

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


theExample = Example()
print theExample.the_example()

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

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


theExample = Example()
print theExample.the_example()
画离情绘悲伤 2024-09-20 08:41:31

如果您有 @classmethod 静态方法,您始终将类作为第一个参数:

class Example(object):
    itsProblem = "problem"

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

Example.printProblem()

If you have a @classmethod static method, you always have the class as the first parameter:

class Example(object):
    itsProblem = "problem"

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

Example.printProblem()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文