将变量作为参数返回给方法的正确方法

2024-04-27 16:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

一个令人困惑的问题

我在一个类中有两个方法:

from example import sample2
class sample1:
      def m1():
           a='apple'
           b='ball'
           return sample2.m3(a,b)
      def m2():
           a='ant'
           b='bat'
           c='cat'
           return sample2.m3(a,b,c)

在示例.py地址:

class sample2:
       def m3("here I want to access any `a`,`b`,`c` of respective m1 and m2"):
            .....

如果这个问题没有意义,我很抱歉,但是当我尝试访问时,仅作为:

class sample1:
      def m1():
           a='apple'
           b='ball'
           return sample2.m3(a,b)

在示例.py地址:

 class sample2:
       def m3(a,b):
           print(a)   

a有值apple,所以类似的方式,为什么我不能从返回的m1m2访问a,b,c的任何值?你知道吗


Tags: 方法frompy示例applereturn地址def
2条回答

Python中的变量总是应用于特定的范围,例如类、函数或闭包。Python使用lexical scoping,这意味着作用域只能通过嵌套在源代码中来连接。最重要的是,不同范围中的变量根本没有连接。你知道吗

当你“传递一个变量”给一个函数时,你实际上只传递了一个值。该变量不存在于其他函数(除非它们是嵌套的)或周围的作用域中。你知道吗

def nested(a):
    a = 3
    print('a =', a)  # a = 3

def parent():
    a = 4
    nested(a)
    print('a =', a)  # a = 4

parent()
print(a)  # NameError: name 'a' is not defined

函数应该主要通过调用输入和return结果来交换数据:

def nested(a):       # receive input
    a = 3
    print('a =', a)  # a = 3
    return a         # return output

def parent():
    a = 4
    a = nested(a)    # replace a with result of nested(a)
    print('a =', a)  # a = 3

parent()

请注意,只传入和返回值。如果在两个函数中重命名a,则上述函数的行为可能完全相同。你知道吗


使用类实例时,实例本身作为命名空间(类似于作用域)。该实例的方法可以通过修改实例的属性来交换数据。实例始终作为第一个参数传递给方法:

class Example():
    """An example for setting attributes on an instance"""
    def __init__(self):
        self.a = 0

    def nested(self):
        self.a = 3
        print('self.a =', self.a)  # self.a = 3

    def parent(self):
        self.a = 4
        print('self.a =', self.a)  # self.a = 4
        self._nested()
        print('self.a =', self.a)  # self.a = 3

instance = Example()
print(instance.a)  # 0
instance.parent()  # self.a = 4
                   # self.a = 3

要在对象之间交换数据,方法还应主要通过调用输入和return结果来交换数据:

class Example():
    """An example for setting attributes on an instance"""
    def __init__(self, a):
        self.a = a

    def multiply(self, value):
        return self.a * value

instance = Example(6)
print(instance.multiply(10))  # 60

这就是你如何使用装饰器。有关decorator如何工作的更多信息,请参见:https://www.datacamp.com/community/tutorials/decorators-python
我建议您首先尝试更好地理解类和对象的概念。示例教程:https://www.w3schools.com/python/python_classes.asp
这篇文章还可以帮助您理解staticmethoddecorator是如何工作的What is the difference between @staticmethod and @classmethod?

from example import sample2

class sample1:
    @staticmethod
    def m1():
        a='apple'
        b='ball'
        return sample2.m3(a,b)

    @staticmethod
    def m2():
        a='ant'
        b='bat'
        c='cat'
        return sample2.m3(a,b,c)

你知道吗示例.py带说明的文件:

class sample2:
    @staticmethod
    def m3(a, b, c=None): # it works exactly the same as m3 function that is outside the class
        print(a)
        # this can be used without creating an object of sample2 class, example:
        # sample2.m3(a="apple, b="ball")

    def m3_method(self, a, b): # this one requires object on which it can be called
        print(a)
        # you have access to sample2 class object via self parameter, example of code:
        # sample2_object = sample2() # you create object of sample2 class here
        # sample2_object.m3_method(a="apple", b="ball") # you call m3_method on sample2_object here


def m3(a, b, c=None): # default value of c is add so you can either call it with 2 or 3 arguments
    # example calls:
    # m3("a", "b")
    # m3("a", "b", "c")
    print(a)

您应该能够运行这段代码,我认为它让您了解如何使用Python类。你知道吗

相关问题 更多 >