Objects vs instance in python

后端 未结 5 1800
情话喂你
情话喂你 2020-12-13 11:29

In C++ there are just objects and classes, where objects are instances of classes.

In Python, a class definition (i.e., the body of a class) is called an object. And

5条回答
  •  悲&欢浪女
    2020-12-13 11:48

    Since you asked for "english please", I'll try to make it simple at the cost of detail.

    Let's ignore classes and instances at first, and just look at objects.

    A Python object contains data and functions, just like objects in every other object oriented programming language. Functions attached to objects are called methods.

    x = "hello" #now x is an object that contains the letters in "hello" as data
    print x.size() #but x also has methods, for example size()
    print "hello".size() #In python, unlike C++, everything is an object, so a string literal has methods.
    print (5).bit_length() #as do integers (bit_length only works in 2.7+ and 3.1+, though)
    

    A class is a description (or a recipe, if you will) of how to construct new objects. Objects constructed according to a class description are said to belong to that class. A fancy name for belonging to a class is to be an instance of that class.

    Now, earlier I wrote that in Python everything is an object. Well, that holds for stuff like functions and classes as well. So a description of how to make new objects is itself an object.

    class C: #C is a class and an object
      a = 1
    
    x1 = C() #x1 is now an instance of C
    print x1.a #and x1 will contain an object a
    
    y = C #Since C is itself an object, it is perfectly ok to assign it to y, note the lack of ()
    x2 = y() #and now we can make instances of C, using y instead.
    print x2.a #x2 will also contain an object a
    
    print C #since classes are objects, you can print them
    print y #y is the same as C.
    print y == C #really the same.
    print y is C #exactly the same.
    

    This means that you can treat classes (and functions) like everything else and, for example, send them as arguments to a function, which can use them to construct new objects of a class it never knew existed.

提交回复
热议问题