python:在另一个类中创建类的实例(带有通用示例) [英] python: create instance of class in another class (with generic example)

查看:514
本文介绍了python:在另一个类中创建类的实例(带有通用示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过书本和互联网学习python,却陷入了课堂问题。

I'm learning python via book and internet and I'm stuck on a class issue.

2个问题:


  1. 如何在另一个(单独的)类中创建一个类的实例?

  2. 如何在类和嵌套类之间传递变量(?)类?

当我尝试在另一个(单独的)类中创建一个类的实例时,我能够用一种方法做到这一点。以下是代码:

When I try to create an instance of a class within another (separate) class, i'm able to do so within a method. Here's the code:

import os

class FOO():
    def __init__(self):
        self.values = [2, 4, 6, 8]

    def do_something(self, x, y):
        os.system("clear")
        z = self.values[x] * self.values[y]
        print "%r * %r = %r" % (self.values[x], self.values[y], z)


class BAR():
    def __init__(self):
        pass

    def something_else(self, a, b):
        foo1 = FOO()
        foo1.do_something(a, b)

bar = BAR()
bar.something_else(1, 2)

但是,请允许我访问FOO类及其其他BAR方法中的信息吗?如果是这样,怎么办?

Will this, however, allow me to access the FOO class and it's information in other BAR methods? If so, how?

我尝试了以下操作并收到错误:

I tried the following and got an error:

import os

class FOO():
    def __init__(self):
        self.values = [2, 4, 6, 8]

    def do_something(self, x, y):
        os.system("clear")
        z = self.values[x] * self.values[y]
        print "%r * %r = %r" % (self.values[x], self.values[y], z)


class BAR():
    def __init__(self):
        foo1 = FOO()

    def something_else(self, a, b):
        foo1.do_something(a, b)

bar = BAR()
bar.something_else(1, 2)

这是错误:

Traceback (most recent call last):
File "cwic.py", line 22, in <module>
bar.something_else(1, 2)
File "cwic.py", line 19, in something_else
foo1.do_something(a, b)
NameError: global name 'foo1' is not defined

使用时遇到相同的错误:

I get the same error when I used:

def __init__(self):
    self.foo1 = FOO()

另外,我应该如何将值从一个类传递到另一类?

Also, how should I pass the 'values' from one class to the other?

请告诉我一般方法和/或语法错误。我正在学习时,欢迎任何和所有建议(包括良好的阅读)。谢谢。

Please let me know if my general approach and/or syntax are wrong. Any and all suggestions welcome (including good reading) as I am just learning. Thanks.

推荐答案

实例或类的所有属性都是通过 self 作为第一个参数传递给所有方法。这就是为什么您正确获得方法签名 something_else(self,a,b)而不是仅仅 something_else(a,b),就像使用其他语言一样。因此,您正在寻找:

All attributes of an instance or class are accessed via self which is passed as the first argument to all methods. That's why you've correctly got the method signature something_else(self, a, b) as opposed to just something_else(a, b) as you might with other languages. So you're looking for:

    class BAR():
        def __init__(self):
            self.foo1 = FOO()

    def something_else(self, a, b):
        self.foo1.do_something(a, b)

请注意,self不是关键字,它只是像 a b ,因此,例如,如果您来自Java背景,则可能会想使用 this 代替...不过!有一个非常强烈的习惯,就是为此目的使用 self ,如果您使用其他任何方法,您会让很多人(最终包括您自己)非常生气!

Note that self isn't a keyword, it's just a paramater name like a and b, so you might for example be tempted to use this instead if you're from a Java background... Don't though! there is a very strong convention to use self for this purpose and you will make a lot of people (including yourself eventually) very angry if you use anything else!

关于传递值,我不确定您的意思是什么,您可以通过 foo1.an_attribute 或将它们作为参数传递给 function(arg)中的参数,但是您似乎在示例中使用了这两种技术,所以我不确定您还打算做什么。 。

With regards to passing values I'm not sure what you mean, you can access them through instances such as foo1.an_attribute or pass them as arguments to functions as in function(arg) but you seem to have used both techniques in your example so I'm not sure what else you're after...

编辑

对于@dwstein的评论,我不是确保在VB中是如何完成的,但是这是在创建类的实例时如何传递参数的方法。

In response to @dwstein's comment, I'm not sure how it's done in VB but here's a how you pass arguments when creating an instance of a class.

如果我们查看您的类:

class BAR():
    def __init__(self):
        self.foo1 = FOO()

我们可以通过将第二行更改为 def __init __(self,baz)将其更改为接受参数baz: 和n如果我们愿意,可以通过设置来使 baz 成为我们的 BAR 新实例的属性self.baz = baz 。希望有帮助。

We can change that to accept an argument baz by changing second line to def __init__(self, baz): and then if we want we can make baz an attribute of our new instance of BAR by setting self.baz = baz. Hope that helps.

这篇关于python:在另一个类中创建类的实例(带有通用示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆