The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python classes - Basics of Python classes, objects, instance methods and variables (3.11.0 docs) and examples
By Guest on 31st October 2022 06:24:12 PM | Syntax: PYTHON | Views: 237



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. Answers to questions:
  2. What are class variables and instance variables in Python?
  3. What is the difference between class and instance variable?
  4. What is an instance variable Python?
  5. What is class and instance in Python?
  6. What is instance method and class method in Python?
  7. What is the difference between instance and class in Python?
  8. What are instance and class methods?
  9. What is instance methods in Python?
  10. Tutorial links are listed below.
  11.  
  12. 9.3.1. Class Definition Syntax
  13. ------------------------------
  14.  
  15. The simplest form of class definition looks like this:
  16.  
  17.    class ClassName:
  18.        <statement-1>
  19.        .
  20.        .
  21.        .
  22.        <statement-N>
  23.  
  24. Class definitions, like function definitions ("def" statements) must
  25. be executed before they have any effect.  (You could conceivably place
  26. a class definition in a branch of an "if" statement, or inside a
  27. function.)
  28.  
  29. In practice, the statements inside a class definition will usually be
  30. function definitions, but other statements are allowed, and sometimes
  31. useful --- we'll come back to this later.  The function definitions
  32. inside a class normally have a peculiar form of argument list,
  33. dictated by the calling conventions for methods --- again, this is
  34. explained later.
  35.  
  36. When a class definition is entered, a new namespace is created, and
  37. used as the local scope --- thus, all assignments to local variables
  38. go into this new namespace.  In particular, function definitions bind
  39. the name of the new function here.
  40.  
  41. When a class definition is left normally (via the end), a *class
  42. object* is created.  This is basically a wrapper around the contents
  43. of the namespace created by the class definition; we'll learn more
  44. about class objects in the next section.  The original local scope
  45. (the one in effect just before the class definition was entered) is
  46. reinstated, and the class object is bound here to the class name given
  47. in the class definition header ("ClassName" in the example).
  48.  
  49.  
  50. 9.3.2. Class Objects
  51. --------------------
  52.  
  53. Class objects support two kinds of operations: attribute references
  54. and instantiation.
  55.  
  56. *Attribute references* use the standard syntax used for all attribute
  57. references in Python: "obj.name".  Valid attribute names are all the
  58. names that were in the class's namespace when the class object was
  59. created.  So, if the class definition looked like this:
  60.  
  61.   class MyClass:
  62.       """A simple example class"""
  63.       i = 12345
  64.  
  65.       def f(self):
  66.           return 'hello world'
  67.  
  68. then "MyClass.i" and "MyClass.f" are valid attribute references,
  69. returning an integer and a function object, respectively. Class
  70. attributes can also be assigned to, so you can change the value of
  71. "MyClass.i" by assignment. "__doc__" is also a valid attribute,
  72. returning the docstring belonging to the class: ""A simple example
  73. class"".
  74.  
  75. Class *instantiation* uses function notation.  Just pretend that the
  76. class object is a parameterless function that returns a new instance
  77. of the class. For example (assuming the above class):
  78.  
  79.   x = MyClass()
  80.  
  81. creates a new *instance* of the class and assigns this object to the
  82. local variable "x".
  83.  
  84. The instantiation operation ("calling" a class object) creates an
  85. empty object. Many classes like to create objects with instances
  86. customized to a specific initial state. Therefore a class may define a
  87. special method named "__init__()", like this:
  88.  
  89.   def __init__(self):
  90.       self.data = []
  91.  
  92. When a class defines an "__init__()" method, class instantiation
  93. automatically invokes "__init__()" for the newly created class
  94. instance.  So in this example, a new, initialized instance can be
  95. obtained by:
  96.  
  97.   x = MyClass()
  98.  
  99. Of course, the "__init__()" method may have arguments for greater
  100. flexibility.  In that case, arguments given to the class instantiation
  101. operator are passed on to "__init__()".  For example,
  102.  
  103.   >>> class Complex:
  104.   ...     def __init__(self, realpart, imagpart):
  105.   ...         self.r = realpart
  106.   ...         self.i = imagpart
  107.   ...
  108.   >>> x = Complex(3.0, -4.5)
  109.   >>> x.r, x.i
  110.   (3.0, -4.5)
  111.  
  112.  
  113. 9.3.3. Instance Objects
  114. -----------------------
  115.  
  116. Now what can we do with instance objects?  The only operations
  117. understood by instance objects are attribute references.  There are
  118. two kinds of valid attribute names: data attributes and methods.
  119.  
  120. *data attributes* correspond to "instance variables" in Smalltalk, and
  121. to "data members" in C++.  Data attributes need not be declared; like
  122. local variables, they spring into existence when they are first
  123. assigned to.  For example, if "x" is the instance of "MyClass" created
  124. above, the following piece of code will print the value "16", without
  125. leaving a trace:
  126.  
  127.   x.counter = 1
  128.   while x.counter < 10:
  129.       x.counter = x.counter * 2
  130.   print(x.counter)
  131.   del x.counter
  132.  
  133. The other kind of instance attribute reference is a *method*. A method
  134. is a function that "belongs to" an object.  (In Python, the term
  135. method is not unique to class instances: other object types can have
  136. methods as well.  For example, list objects have methods called
  137. append, insert, remove, sort, and so on. However, in the following
  138. discussion, we'll use the term method exclusively to mean methods of
  139. class instance objects, unless explicitly stated otherwise.)
  140.  
  141. Valid method names of an instance object depend on its class.  By
  142. definition, all attributes of a class that are function  objects
  143. define corresponding methods of its instances.  So in our example,
  144. "x.f" is a valid method reference, since "MyClass.f" is a function,
  145. but "x.i" is not, since "MyClass.i" is not.  But "x.f" is not the same
  146. thing as "MyClass.f" --- it is a *method object*, not a function
  147. object.
  148.  
  149.  
  150. 9.3.4. Method Objects
  151. ---------------------
  152.  
  153. Usually, a method is called right after it is bound:
  154.  
  155.    x.f()
  156.  
  157. In the "MyClass" example, this will return the string "'hello world'".
  158. However, it is not necessary to call a method right away: "x.f" is a
  159. method object, and can be stored away and called at a later time.  For
  160. example:
  161.  
  162.    xf = x.f
  163.    while True:
  164.        print(xf())
  165.  
  166. will continue to print "hello world" until the end of time.
  167.  
  168. What exactly happens when a method is called?  You may have noticed
  169. that "x.f()" was called without an argument above, even though the
  170. function definition for "f()" specified an argument.  What happened to
  171. the argument? Surely Python raises an exception when a function that
  172. requires an argument is called without any --- even if the argument
  173. isn't actually used...
  174.  
  175. Actually, you may have guessed the answer: the special thing about
  176. methods is that the instance object is passed as the first argument of
  177. the function.  In our example, the call "x.f()" is exactly equivalent
  178. to "MyClass.f(x)".  In general, calling a method with a list of *n*
  179. arguments is equivalent to calling the corresponding function with an
  180. argument list that is created by inserting the method's instance
  181. object before the first argument.
  182.  
  183. If you still don't understand how methods work, a look at the
  184. implementation can perhaps clarify matters.  When a non-data attribute
  185. of an instance is referenced, the instance's class is searched.  If
  186. the name denotes a valid class attribute that is a function object, a
  187. method object is created by packing (pointers to) the instance object
  188. and the function object just found together in an abstract object:
  189. this is the method object.  When the method object is called with an
  190. argument list, a new argument list is constructed from the instance
  191. object and the argument list, and the function object is called with
  192. this new argument list.
  193.  
  194.  
  195. 9.3.5. Class and Instance Variables
  196. -----------------------------------
  197.  
  198. Generally speaking, instance variables are for data unique to each
  199. instance and class variables are for attributes and methods shared by
  200. all instances of the class:
  201.  
  202.    class Dog:
  203.  
  204.        kind = 'canine'         # class variable shared by all instances
  205.  
  206.        def __init__(self, name):
  207.            self.name = name    # instance variable unique to each instance
  208.  
  209.    >>> d = Dog('Fido')
  210.    >>> e = Dog('Buddy')
  211.    >>> d.kind                  # shared by all dogs
  212.    'canine'
  213.    >>> e.kind                  # shared by all dogs
  214.    'canine'
  215.    >>> d.name                  # unique to d
  216.    'Fido'
  217.    >>> e.name                  # unique to e
  218.    'Buddy'
  219.  
  220. As discussed in A Word About Names and Objects, shared data can have
  221. possibly surprising effects with involving *mutable* objects such as
  222. lists and dictionaries. For example, the *tricks* list in the
  223. following code should not be used as a class variable because just a
  224. single list would be shared by all *Dog* instances:
  225.  
  226.    class Dog:
  227.  
  228.        tricks = []             # mistaken use of a class variable
  229.  
  230.        def __init__(self, name):
  231.            self.name = name
  232.  
  233.        def add_trick(self, trick):
  234.            self.tricks.append(trick)
  235.  
  236.    >>> d = Dog('Fido')
  237.    >>> e = Dog('Buddy')
  238.    >>> d.add_trick('roll over')
  239.    >>> e.add_trick('play dead')
  240.    >>> d.tricks                # unexpectedly shared by all dogs
  241.    ['roll over', 'play dead']
  242.  
  243. Correct design of the class should use an instance variable instead:
  244.  
  245.    class Dog:
  246.  
  247.        def __init__(self, name):
  248.            self.name = name
  249.            self.tricks = []    # creates a new empty list for each dog
  250.  
  251.        def add_trick(self, trick):
  252.            self.tricks.append(trick)
  253.  
  254.    >>> d = Dog('Fido')
  255.    >>> e = Dog('Buddy')
  256.    >>> d.add_trick('roll over')
  257.    >>> e.add_trick('play dead')
  258.    >>> d.tricks
  259.    ['roll over']
  260.    >>> e.tricks
  261.    ['play dead']
  262.  
  263. Practice with Python class syntax and instance variables.
  264. Video references with examples and tutorials:
  265.  
  266. Understand Classes & Objects in 8 Minutes
  267. https://www.youtube.com/watch?v=BM9tPve8T1o
  268.  
  269. Python Object Oriented Programming (OOP) - For Beginners
  270. https://www.youtube.com/watch?v=JeznW_7DlB0
  271.  
  272. Python As Fast as Possible - Learn Python in ~75 Minutes
  273. https://www.youtube.com/watch?v=VchuKL44s6E
















Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.

Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license
  • Recent Pastes