小白教程

 找回密码
 立即注册

init 方法

发布者: 小白教程

在Python类中,有许多方法名称具有特殊的意义。现在,我们将看到该__init__方法的重要性

__init__实例化(即创建)类的对象后,将立即运行方法。该方法对于执行您想对对象进行的任何初始化(即,将初始值传递给您的对象)很有用。请注意,该名称的开头和结尾均带有双下划线。

示例(另存为oop_init.py):

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

    def say_hi(self):
        print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()
# The previous 2 lines can also be written as
# Person('Swaroop').say_hi()

输出:

$ python oop_init.py
Hello, my name is Swaroop

这个怎么运作

在这里,我们将__init__方法定义为采用参数name(以及通常的self)。在这里,我们只创建了一个新字段,也称为name请注意,尽管这两个变量都被称为“名称”,但它们是两个不同的变量。没问题,因为点号表示self.name存在一个叫做“名称”的东西,它是对象“自我”的一部分,另一个name是局部变量。由于我们明确指出了要指代的名称,因此不会造成混淆。

创建类的新实例时pPerson我们使用类名,然后在括号中加上参数:p = Person('Swaroop')。

我们没有显式调用该__init__方法。这是此方法的特殊意义。

现在,我们可以self.name在方法中使用该字段,该方法已得到证明say_hi

类和对象变量

我们已经讨论了类和对象(即方法)的功能部分,现在让我们了解数据部分。数据部分(即字段)不过是绑定类和对象名称空间普通变量这意味着这些名称仅在这些类和对象的上下文中有效。这就是为什么它们被称为名称空间

有两种类型的字段-类变量和对象变量,它们分别根据类或对象是否拥有变量进行分类

类变量是共享的-该类的所有实例都可以访问它们。类变量只有一个副本,并且当任何一个对象对类变量进行更改时,所有其他实例都可以看到该更改。

对象变量由该类的每个单独对象/实例拥有。在这种情况下,每个对象都有其自己的字段副本,即,它们在不同实例中不被共享并且不以相同的方式以任何方式与该字段相关。一个示例将使这一点易于理解(另存为oop_objvar.py):

class Robot:
    """Represents a robot, with a name."""

    # A class variable, counting the number of robots
    population = 0

    def __init__(self, name):
        """Initializes the data."""
        self.name = name
        print("(Initializing {})".format(self.name))

        # When this person is created, the robot
        # adds to the population
        Robot.population += 1

    def die(self):
        """I am dying."""
        print("{} is being destroyed!".format(self.name))

        Robot.population -= 1

        if Robot.population == 0:
            print("{} was the last one.".format(self.name))
        else:
            print("There are still {:d} robots working.".format(
                Robot.population))

    def say_hi(self):
        """Greeting by the robot.

        Yeah, they can do that."""
        print("Greetings, my masters call me {}.".format(self.name))

    @classmethod
    def how_many(cls):
        """Prints the current population."""
        print("We have {:d} robots.".format(cls.population))


droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()

Robot.how_many()

输出:

$ python oop_objvar.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.

这个怎么运作

这是一个很长的示例,但有助于说明类和对象变量的性质。在这里,population属于Robot该类,因此是一个类变量。name变量属于对象(它是使用分配

上一篇:面向对象编程下一篇:重用

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:35 , Processed in 0.019205 second(s), 18 queries .