Python-类构造器__init__方法
时间:2020-02-23 14:42:30 来源:igfitidea点击:
在本教程中,我们将学习Python中的类__init__方法。
我们在Python-Classes and Objects教程中了解了类以及如何使用类创建对象。
随时检查一下。
__init__方法
__init__方法是类的一种特殊方法。
它也称为构造函数方法,当我们创建(实例化)该类的对象时调用它。
我们使用__init__方法来初始化类属性或者调用类方法。
在下面的Python程序中,我们在Awesome类内创建__init__方法。
# class
class Awesome:
# the init method
def __init__(self):
print("Hello from the __init__ method.")
# object of the class
obj = Awesome()
上面的代码将打印以下输出。
Hello from the __init__ method.
我们得到上面的输出,因为一旦创建类的对象,就会自动调用__init__方法。
注意点!
__init__方法的第一个参数始终是self。
" self"是指类的对象,我们使用它来从类内部访问方法和类属性。
将参数传递给__init__方法
与类的其他任何方法一样,我们也可以将参数传递给__init__方法。
在下面的Python程序中,我们在创建对象时将字符串值传递给__init__方法。
# class
class Awesome:
# the init method
def __init__(self, name):
print("Hello from the __init__ method.")
print("Name:", name)
# object of the class
obj = Awesome("theitroad")
上面的代码将为我们提供以下输出。
Hello from the __init__ method. Name: theitroad
从__init__方法中调用其他方法
我们可以通过使用self关键字从__init__方法调用该类的其他方法。
# class
class Awesome:
# the init method
def __init__(self):
print("Hello from the __init__ method.")
# calling the class method
self.greetings()
# methods
def greetings(self):
print("Hello from the greetings() method.")
# object of the class
obj = Awesome()
上面的代码将打印以下输出。
Hello from the __init__ method. Hello from the greetings() method.
在__init__方法内初始化类属性
我们可以创建特定于类对象的类属性,并在__init__方法内部对其进行初始化。
在下面的Python程序中,我们将在__init__方法内创建Awesome类并初始化类属性name。
# class
class Awesome:
# class attribute common to all objects
commonAttr = "Common Attribute"
# the init method
def __init__(self, name):
# class attribute for the objects
self.name = name
# methods
def greetings(self):
print("Hello %s!" %self.name)
# object of the class
obj1 = Awesome("Tom")
obj2 = Awesome("Jerry")
# output
print("The common class attribute:")
print("obj1.commonAttr:", obj1.commonAttr)
print("obj2.commonAttr:", obj2.commonAttr)
print("Class attribute specific to object:")
print("obj1.greetings():")
obj1.greetings()
print("obj2.greetings():")
obj2.greetings()
上面的代码将打印以下输出。
The common class attribute: obj1.commonAttr: Common Attribute obj2.commonAttr: Common Attribute Class attribute specific to object: obj1.greetings(): Hello Tom! obj2.greetings(): Hello Jerry!

