简体   繁体   English

如果涉及方法内部变量的scope,python与java是否不同?

[英]Is python different from java if the scope of the variable inside a method is concerned?

I am writing the following code:我正在编写以下代码:

class NewList():

    def __init__(self,initial_state):
        self.data = initial_state

    def append(self,new_item):
        self.data = self.data + [new_item]
        self.big = self.data

    def deppend(self,new_item):
        self.data = self.data + [new_item]
        self.big = self.big + [new_item]


    my_list = NewList([1,2,3,4,5])
    print(my_list.data)
    my_list.append(6)
    print(my_list.data)
    print(my_list.big)
    my_list.deppend(7)
    print(my_list.data)
    print(my_list.big)

I don't think variables such as data,big etc that are declared inside a method can be used in another method in Java. But, here in python we are easily able to use them.我认为在 Java 中的另一个方法中不能使用在一个方法中声明的诸如 data、big 等变量。但是,在 python 中,我们可以轻松地使用它们。 Is it that the variables declared inside a method in python have a global scope rather than java that has a local scope??是否在 python 中的方法内部声明的变量具有全局 scope 而不是具有局部 scope 的 java?

The variable you have defined are declared using self keyword.您定义的变量是使用self关键字声明的。 Think of it as this in java.把它想象成 java 中的this

So when you do self.big = self.data The big becomes the attribute of the object. Hence it is accessible with the object.因此,当您执行self.big = self.data时,big 成为 object 的属性。因此可以使用 object 访问它。

obj.attribute and self.attribute are essentially the same. obj.attributeself.attribute本质上是一样的。 And in python, you can create new attributes at fly.在 python 中,您可以随时创建新属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM