Python 变量声明 [英] Python Variable Declaration

查看:74
本文介绍了Python 变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Python,有一些基本的疑惑.

Learning Python, and has some basic doubts.

1.我已经看到 变量声明(此处的路径)为

1.I have seen variable declaration (path here) as

class writer:
    path = ""

有时,没有显式声明而是通过__init__初始化.

sometimes, no explicit declaration but initialize through __init__.

def __init__(self, name):
    self.name = name

我理解 __init__ 的目的,但是否建议在任何其他函数中声明变量.

I understand the purpose of __init__, but is it advisable to declare variable in any other functions.

2.如何创建变量来保存自定义类型?

2.How can I create variable to hold a custom type?

class writer:
    path = "" # string value
    customObj = ??

推荐答案

好的,第一件事.

Python 中没有变量声明"或变量初始化"这样的东西.

我们简单地称之为赋值",但可能应该称之为命名".

There is simply what we call "assignment", but should probably just call "naming".

赋值意味着左边的这个名字现在指的是评估右边的结果,不管它之前指的是什么(如果有的话)".

Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regardless of what it referred to before (if anything)".

foo = 'bar' # the name 'foo' is now a name for the string 'bar'
foo = 2 * 3 # the name 'foo' stops being a name for the string 'bar',
# and starts being a name for the integer 6, resulting from the multiplication

因此,Python 的名称(可以说是比变量"更好的术语,可以说)没有关联类型;价值观.无论其类型如何,您都可以将相同的名称重新应用于任何事物,但该事物仍然具有依赖于其类型的行为.名称只是引用值(对象)的一种方式.这回答了您的第二个问题:您创建变量来保存自定义类型.您不会创建变量来保存任何特定类型.您根本不创建"变量.您为对象命名.

As such, Python's names (a better term than "variables", arguably) don't have associated types; the values do. You can re-apply the same name to anything regardless of its type, but the thing still has behaviour that's dependent upon its type. The name is simply a way to refer to the value (object). This answers your second question: You don't create variables to hold a custom type. You don't create variables to hold any particular type. You don't "create" variables at all. You give names to objects.

第二点:当涉及到类时,Python 遵循一个非常简单的规则,这实际上比 Java、C++ 和 C# 之类的语言更一致:class 中声明的所有内容块是类的一部分.因此,这里编写的函数 (def) 是方法,即类对象的一部分(不存储在每个实例的基础上),就像在 Java、C++ 和 C# 中一样;但这里的其他名字是班级的一部分.同样,名称只是名称,它们没有关联的类型,在 Python 中函数也是对象.因此:

Second point: Python follows a very simple rule when it comes to classes, that is actually much more consistent than what languages like Java, C++ and C# do: everything declared inside the class block is part of the class. So, functions (def) written here are methods, i.e. part of the class object (not stored on a per-instance basis), just like in Java, C++ and C#; but other names here are also part of the class. Again, the names are just names, and they don't have associated types, and functions are objects too in Python. Thus:

class Example:
    data = 42
    def method(self): pass

类也是对象,在 Python 中.

Classes are objects too, in Python.

所以现在我们创建了一个名为Example对象,它代表所有属于Example的事物的类.该对象有两个用户提供的属性(在 C++ 中,成员";在 C# 中,字段或属性或方法";在 Java 中,字段或方法").其中之一名为data,它存储整数值42.另一个名为method,它存储一个函数对象.(还有几个属性是 Python 自动添加的.)

So now we have created an object named Example, which represents the class of all things that are Examples. This object has two user-supplied attributes (In C++, "members"; in C#, "fields or properties or methods"; in Java, "fields or methods"). One of them is named data, and it stores the integer value 42. The other is named method, and it stores a function object. (There are several more attributes that Python adds automatically.)

不过,这些属性仍然不是对象的真正组成部分.从根本上说,一个对象只是一堆更多的名称(属性名称),直到您深入了解无法再分割的事物为止.因此,值可以在类的不同实例之间共享,甚至可以在不同类的对象之间共享,如果您有意设置的话.

These attributes still aren't really part of the object, though. Fundamentally, an object is just a bundle of more names (the attribute names), until you get down to things that can't be divided up any more. Thus, values can be shared between different instances of a class, or even between objects of different classes, if you deliberately set that up.

让我们创建一个实例:

x = Example()

现在我们有一个名为x的独立对象,它是Example的一个实例.datamethod 实际上不是对象的一部分,但我们仍然可以通过 x 查找它们,因为 Python 在背后做了一些魔法场景.当我们查找 method 时,特别地,我们会得到一个绑定方法"(当我们调用它时,x 会自动作为 self 传递code> 参数,如果我们直接查找Example.method 不会发生这种情况).

Now we have a separate object named x, which is an instance of Example. The data and method are not actually part of the object, but we can still look them up via x because of some magic that Python does behind the scenes. When we look up method, in particular, we will instead get a "bound method" (when we call it, x gets passed automatically as the self parameter, which cannot happen if we look up Example.method directly).

当我们尝试使用 x.data 时会发生什么?

What happens when we try to use x.data?

当我们检查它时,它首先在对象中查找.如果在对象中没有找到,Python 会在类中查找.

When we examine it, it's looked up in the object first. If it's not found in the object, Python looks in the class.

然而,当我们赋值给 x.data 时,Python 会在对象上创建一个属性.它将替换类的属性.

However, when we assign to x.data, Python will create an attribute on the object. It will not replace the class' attribute.

这允许我们进行对象初始化.Python 将在新实例创建时自动调用类的 __init__ 方法(如果存在).在这个方法中,我们可以简单地分配给属性来为每个对象上的属性设置初始值:

This allows us to do object initialization. Python will automatically call the class' __init__ method on new instances when they are created, if present. In this method, we can simply assign to attributes to set initial values for that attribute on each object:

class Example:
    name = "Ignored"
    def __init__(self, name):
        self.name = name
    # rest as before

现在我们在创建Example时必须指定一个name,并且每个实例都有自己的name.每当我们查找实例的 .name 时,Python 都会忽略类属性 Example.name,因为会先找到实例的属性.

Now we must specify a name when we create an Example, and each instance has its own name. Python will ignore the class attribute Example.name whenever we look up the .name of an instance, because the instance's attribute will be found first.

最后一个警告:修改(变异)和赋值是不同的事情!

在 Python 中,字符串是不可变的.它们不能被修改.当你这样做时:

In Python, strings are immutable. They cannot be modified. When you do:

a = 'hi '
b = a
a += 'mom'

不要更改原始的hi"字符串.这在 Python 中是不可能的.相反,您创建了一个 new 字符串 'hi mom',并使 a 不再是 'hi ',并开始成为 'hi mom' 的名字.我们也为 'hi ' 设置了 b 名称,重新应用 a 名称后,b仍然是 'hi ' 的名字,因为 'hi ' 仍然存在并且没有被改变.

You do not change the original 'hi ' string. That is impossible in Python. Instead, you create a new string 'hi mom', and cause a to stop being a name for 'hi ', and start being a name for 'hi mom' instead. We made b a name for 'hi ' as well, and after re-applying the a name, b is still a name for 'hi ', because 'hi ' still exists and has not been changed.

但是列表可以更改:

a = [1, 2, 3]
b = a
a += [4]

现在 b 也是 [1, 2, 3, 4],因为我们给 b 取了一个名称,表示 a> 命名,然后我们改变了那个东西.我们没有为 a 创建一个新列表来命名,因为 Python 只是对列表的 += 进行了不同的处理.

Now b is [1, 2, 3, 4] as well, because we made b a name for the same thing that a named, and then we changed that thing. We did not create a new list for a to name, because Python simply treats += differently for lists.

这对对象很重要,因为如果您有一个列表作为类属性,并使用一个实例来修改列表,那么更改将在所有其他实例中看到".这是因为 (a) 数据实际上是类对象的一部分,而不是任何实例对象;(b) 因为您是在修改列表而不是进行简单的赋值,所以您没有创建隐藏类属性的新实例属性.

This matters for objects because if you had a list as a class attribute, and used an instance to modify the list, then the change would be "seen" in all other instances. This is because (a) the data is actually part of the class object, and not any instance object; (b) because you were modifying the list and not doing a simple assignment, you did not create a new instance attribute hiding the class attribute.

这篇关于Python 变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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