When defining a class, if you add the __init__ method, when you create an instance of the class, the instance automatically calls this method, which is typically used to initially make the properties of the instance. Like what:
Class TestClass:
def __init__ (self, Name, gender)://define __INIT__ method, here are three parameters, this is the instance of the creation of the example of the creation of a class instance itself (Testman in the example), you can also write other things, For example, it is possible to write me, so the following self. Name will be written me.name.
Self. Name=name//will usually be written self.name=name, here in order to distinguish between the two is different east, the front of the upper case, the name of the left side of the equal sign (or name) is the attribute of the instance, the latter is the method __init__ parameters, two are different)
Self. Gender=gender//will usually be written Self.gender=gender
Print (' hello ')//This print (' Hello ') is to show that the __init__ method is called immediately when creating an instance of the class.
Testman = TestClass (' Neo, ' Male ')//Create an instance of class TestClass here Testman, the class has __init__ this method, when creating an instance of the class, you must have and method __init__ matching parameters, Since self refers to the created instance itself, it does not have to be passed in, so there are two parameters passed in. As soon as this statement comes out, the two attributes of the instance Testman Name,gender are initially made, where name is Neo,gender male.
1 classTestClass (object):2 def __init__(self, Name, gender):3Self. Name =name4Self. Gender =Gender5 Print('Hello')6 7 8Testman = TestClass ('Neo','male')9 Print(Testman. Name)Ten Print(Testman. Gender) One A - classTetsClass2 (object): - def __init__(Me, Name, gender): theMe.Name =name -Me.gender =Gender - Print("Hello2") -Testman2 = TetsClass2 ('Neo','male') + Print(Testman2.name) - Print(Testman2.gender)
How to use Python's __init__