Some interesting things in the class

Source: Internet
Author: User

1. Example one class is a type, and the built-in type (Int,float) is also a class

class Myclass ():    Pass Print (Type (Myclass)) Print (Type (Myclass ())) Print (Type (0)) Print (Type (int))

Results

<class' type' ><class'__main__. Myclass'><class'int'><class'  type'>

So, 3.0 is unified, the class is a type, int is a type, and a type is a type.

Example two: all objects

def fn (self,name='World'):    print('Hello, %s. '%= Type ('Hello', (object,), Dict (HELLO=FN))   # the function can be assigned a value h=Hello () H.hello ()   #Hello, world.

Above, the function is an object

classobjectcreator ():PassPrint(Objectcreator)defEcho (o):Print(O) echo (objectcreator)#It can be passed as a parameter to a functionObjectcreator.newattr ='Foo'Print(Hasattr (Objectcreator,'newattr')) ObjectCreator2=objectcreator#You can assign it to a variablePrint(ObjectCreator2 ())

Operation Result:

<class ' __main__. Objectcreator ' ><class ' __main__. Objectcreator ' >true<__main__. Objectcreator Object at 0x0027b430>

Above, the class is also an object

Example three: about "self"

First, the method is a class property, not an instance property. The methods in the Self,self class have a representation of the instance that is used to reference a method in a class instance method. Because an instance of a method is always passed by the first argument in any method call, self is selected to represent the instance.

class C ():     def Test (self):         Print ('got it') c=C ()
Print (c.test) #类属性, which represents a function print (c.test) #这样行!!!

Show results

<function c.test at 0x006f36f0><bound method C.test of <__main__. C object at 0x001fb490>>got itgot it

The following code can also be line

class C ():     def Test (self):         Print ('got it') class P (C):     def Test (self):         Print ('got it 2')         Pass p=p () c.test (p)     #got itp.test ()    #got it 2

Example four: __new__ and __init__ differences

In the instance creation process, the __new__ method is called before the __init__ method, because all __new__ methods are class methods, so the first parameter passed in to the class is the class, which is generally represented by a CLS.

If no other special processing is required, you can use the __new__ method of object to get the instance created (that is, self).

We can then find that this instance can actually be obtained using the __new__ method class of other classes, as long as the class or its parent class or ancestor has a __new__ method.

Class another (object):  def __new__ (Cls,*args,**kwargs):    print ("Newano")    return object.__new__ (CLS, * Args, **kwargs) class display (object):  def __init__ (self, *args, **kwargs):    print ("Init")  def __new__ (CLS , *args, **kwargs):    print ("Newdis")    print (Type (CLS))    return another.__new__ (CLS, *args, **kwargs) a= Display ()

Run results

Newdis<class ' type ' >newanoinit

Example five: subclasses of standard types

1A=dict (('Wangzixuan', 12), ('Wangzifeng', 13), ('Lingmiaoqiang', 14)))2 Print(Sorted (A.keys ()))3 4 classsortedkeydict (dict):5     defkeys (self):6         returnSorted (Super (sortedkeydict,self). Keys ())#This sentence must use Super (sortedkeydict,self), if using self will error7A=sortedkeydict (('Wangzixuan', 12), ('Wangzifeng', 13), ('Lingmiaoqiang', 14)))Print(A.keys ())
Run results
['lingmiaoqiang'wangzifeng'Wangzixuan  '['lingmiaoqiang'Wangzifeng ' ' Wangzixuan ']

Explanation: When creating an instance, because the class we call is the base class for dict, except for the self () other built-in functions have not changed, so the seventh line is equivalent to the first row.

Because the Dict class (yes, Dict is a class), instance a uses A.keys () to extract the dictionary's keys, so we can redefine the keys () function so that the keys of the dictionary can be extracted and sorted, so call the methods in the Dict class, see line 6th.

Example Six

Some interesting things in 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.