Instances of the class

Source: Internet
Author: User

Class instantiation: The instantiation of a class is the assignment of a class to a different object.

1. Instantiated objects:

class Newclass ():     Pass # instantiate a class directly as an expression called a function:>>> NEWOBJ = Newclass ()

2. Initialize the instance with the __init__ constructor:

>>>classNewclass ():Pass>>> NEWOBJ =Newclass ()>>>classNewclass ():def __init__(self,name): Self.name=name#if the __init__ function of the class has parameters and is not a default parameter, the arguments must be passed in when instantiating, otherwise an error will be given:>>> NEWOBJ =Newclass () Traceback (most recent): File"<pyshell#21>", Line 1,inch<module>NEWOBJ=Newclass () TypeError:__init__() Missing 1 required positional argument:'name'>>> NEWOBJ = Newclass ('New Class')>>>Newobj.name'New Class'>>>#Here you can see that the parameters of the __init__ function are the same as the parameters in the normal function:>>>classNewclass ():def __init__(self,name='New Class'): Self.name=name>>> NEWOBJ =Newclass ()>>>Newobj.name'New Class'>>>

3, __del__ destructor, when the instance is deleted will call this destructor, and class initialization is the inverse process.

>>>classInsttrack (): Count=0def __init__(self): Insttrack.count+ = 1def __del__(self): Insttrack.count-= 1defHowmany (self):returnInsttrack.count>>> A =Insttrack ()>>> B =Insttrack ()>>>ID (a)1786701000432>>>ID (b)1786701000544>>>A.howmany ()2>>>B.howmany ()2>>>dela>>>B.howmany ()1>>>delb>>>insttrack.count0

Second, instance properties

1, the static property is set by __init__ () constructor;

2. Provide default properties through the __init__ () constructor: The default parameter is the same as the function definition;

3, __init__ () should not have a return statement, should not return the object, or should return none (even if a function does not show the write return statement, but will still return to none by default), because the __init__ constructor is called by default when instantiated. So if there is a return statement, then the instance is the returned object, not the instance returned by the class, such as:

#If you return a value other than none, an error will be given when instantiating:>>>classMyClass ():def __init__(self):Print("Initialized ...")        return1 >>> mc =MyClass () Initialized ... Traceback (most recent): File"<pyshell#48>", Line 1,inch<module>MC=MyClass () TypeError:__init__() shouldreturnNone, not 'int'#when you return to Nnone, you will not get an error:>>>classMyClass ():def __init__(self):Print("Initialized ...")        returnNone>>> MC =MyClass () Initialized ...>>>

Third, view instance properties

1. The Dir () built-in function looks at the class properties:

>>>classExample ():Pass>>> Ex.user ='Root'
>>> ex = Example ()
>>> Ex.pri = 775>>>dir (Example) ['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__']>>> >>>dir (ex) ['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','pri','User']>>>

2. __dict__ (): Dictionary of Instance Properties

class Example ():     Pass>>> ex = Example ()'root'>>> ex.pri = 775>> > ex.__dict__{'pri'user'  'root'}

3, __class__ (): You can check which class the instance object is initialized from

>>> ex.__class__<class'__main__. Example'

Iv. class attributes and instance properties

1. Class attributes can be obtained and modified by instance, and instance properties can only be obtained and modified by instance.

>>>classExample (): Version= 1.2#defines a static member property of a class>>> ex =Example ()#when an attribute is not created in the instance, it is looked up through the class and the base class, and can be returned when found:>>>ex.version1.2#A class can call its own static property>>>example.version1.2#class to modify class properties:>>> example.version = 1.3>>>example.version1.3#The instance properties are also changed when viewed:>>>ex.version1.3>>>#However, this adds a new property with the same name to the instance, which is a property of this instance, separate from the properties of the class:>>> ex.version = 1.0>>>ex.version1.0#you can see that the class properties are unchanged:>>>example.version1.3#at this point, a new instance is instantiated, and its property values are the default class properties:>>> EX2 =Example ()>>>ex2.version1.3#Once the ex instance properties are removed again, the value of the Class property is accessed again:>>>delex.version>>>ex.version1.3

V. Binding of calls and methods

1, call the binding method: that is, through the instance calls the method bound on the instance, when the actual call does not need to pass in the argument of self, the self as the first parameter is passed by default.

>>>classsaysomething ():def __init__(Self,sayword ='hello,world!'): Self.sayword=SayworddefSay (self):Print(Self.sayword)>>> say1 =saysomething ()#to invoke a binding method through an instance:>>>Say1.say () hello,world!#An error is encountered when invoking a bound method through the class:>>>Saysomething.say () Traceback (most recent): File"<pyshell#150>", Line 1,inch<module>Saysomething.say () Typeerror:say () Missing1 Required positional argument:' Self'>>>

2. Call a non-binding method: The most common method of overriding a parent class in a subclass, such as overriding the parent class constructor in the __init__ () constructor of a subclass, but the incoming self parameter must be displayed when called, the interpreter will know that it needs to initialize a class instead of an instance bound on the class:

class Sayoneword (saysomething):     def __init__ (self):        SaySomething. __init__ (self)         >>> say2 = Sayoneword ()>>> Say2.say () hello,world!

Instances of the class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.