Class and object learning tutorials in Python object-oriented programming _python

Source: Internet
Author: User
Tags class definition instance method wrapper python list in python

Everything in Python is an object. class provides a mechanism for creating new types of objects. In this tutorial, we don't talk about class and object-oriented basics, but focus on a better understanding of Python object-oriented programming. Let's say we use the new style Python class, which inherits from the object parent class.
Defining Classes

A class statement can define a series of properties, variables, and methods that are shared by instance objects of the class. A simple class definition is given below:

Class Account (object):
  num_accounts = 0
 
  def __init__ (self, Name, balance):
   self.name = name
   Self.balance = Balance
   account.num_accounts + 1
 
  def del_account (self):
   account.num_accounts-= 1
 
  def Deposit (Self, AMT):
   self.balance = Self.balance + amt
 
  def withdraw (self, AMT):
   self.balance = Self.balance-amt
 
  def inquiry (self): return
   self.balance

The class definition introduces the following new objects:

Class object
Instance Object
Method Object

Class object

When a class definition is encountered during program execution, a new namespace is created that contains the name bindings for all class variables and method definitions. Note The namespace does not create a new local scope that the class method can use, so accessing the variable in the method requires a fully qualified name. The account class in the previous section demonstrates this attribute; The method that attempts to access the num_of_accounts variable needs to be account.num_of_accounts with a fully qualified name, otherwise, if the fully qualified name is not used in the __init__ method, The following error is raised:

Class Account (object):
 num_accounts = 0
 
 def __init__ (self, Name, balance):
  self.name = name
  Self.balance = Balance
  num_accounts + + 1
 
 def del_account (self):
  account.num_accounts-= 1
 
 def deposit ( Self, AMT):
  self.balance = Self.balance + amt
 
 def withdraw (self, AMT):
  self.balance = Self.balance-amt
   def inquiry (self): return
  self.balance
 
>>> acct = account (' Obi ', ten)
Traceback (most recent  Call last):
 File "Python", line 1, in <module>
 File "Python", line 9, in __init__
unboundlocalerror: Local variable ' num_accounts ' referenced before assignment

At the end of a class definition, a class object is created. The scope that is valid before entering the class definition is now restored, and the class object is bound to the class name of the class definition header.

First off the subject, you might ask, if the class you are creating is an object, what is the class of the class object? Consistent with the Python philosophy that everything is an object, class objects do have a class, the type class in the new Python style class.

>>> type (account)
<class ' type ' >

To make you more confused, the account type is type. The type class is a meta class that you can use to create other classes, which we'll introduce later in the tutorial.

class objects support attribute references and instantiations. A property is referenced by a standard point syntax, which is followed by a period and then by a property name: Obj.name. A valid property name is all the variables and method names that appear in the class namespace after the class object is created. For example:

>>> account.num_accounts
>>> 0
>>> account.deposit
>>> <unbound Method account.deposit>

Class instantiation uses function notation. The instantiation invokes the class object as if it were a normal function without arguments, as the account class in the following article:

>>> account ()


After the class object is instantiated, the instance object is returned, and if the __init__ method is defined in the class, the instance object is passed as the first argument. This method will perform user-defined initialization processes, such as initialization of instance variables. For example, account name and balance are set, and the number of instance objects increases by 1.
Instance Object

If the class object is a cookie cutter, the cookie is the result of instantiating the class object. All valid actions on an instance object are references to properties, data, and method objects.
Method Object

Method objects and function objects are similar. If X is an instance of the account class, X.deposit is an example of a method object. There is an additional parameter in the method definition, self. Self points to the class instance. Why do we need to pass the instance as a parameter to the method? Method calls can best illustrate:

>>> x = account ()
>>> x.inquiry ()
10

What happens when an instance method call occurs? You should note that the X.inquiry () call has no parameters, although the method definition contains the self parameter. So what happened to this parameter?

The special thing is that the object that the method acts on is passed through as the first parameter of the function. In our case, the call to X.inquiry () is equivalent to ACCOUNT.F (x). In general, the method that calls the N parameter is equivalent to inserting a method's object into the first parameter position.

The Python tutorial says:

When the referenced instance property is not a data property, the class is searched. If the name represents a legitimate function object, instance objects and function objects will be packaged into an abstract object, the method object. When a method object containing a parameter list is invoked, a new argument list is created based on the instance object and argument list, and the function object is invoked with the new argument list.

This applies to all instance method objects, including the __init__ method. The self argument is not actually a keyword, and any valid parameter names can be used, as shown in the Account class definition:

Class Account (object):
 num_accounts = 0
 
 def __init__ (obj, name, balance):
  obj.name = name
  obj.balance = Balance
  account.num_accounts + + 1
 
 def del_account (obj):
  account.num_accounts-= 1
 
 def deposit (obj, AMT):
  obj.balance = Obj.balance + amt
 
 def withdraw (obj, amt):
  obj.balance = Obj.balance-amt
 
 def inqu Iry (obj): return
  obj.balance
 
>>> account.num_accounts
>>> 0
>>> x = Account (' Obi ', 0)
>>> x.deposit (a)
>>> account.inquiry (x)
>>> 10

Static and Class methods

The method defined in the class is invoked by default by the instance. However, we can also define static or class methods through the corresponding @staticmethod and @classmethod adorners.
static Method

Static mode is a normal function in a class namespace. A static method that references a class returns a function type, not an unbound method type:

Class Account (object):
 num_accounts = 0
 
 def __init__ (self, Name, balance):
  self.name = name
  Self.balance = Balance
  account.num_accounts + 1
 
 def del_account (self):
  account.num_accounts-= 1
 
 def Deposit (Self, AMT):
  self.balance = Self.balance + amt
 
 def withdraw (self, AMT):
  self.balance = Self.balance-amt
 
 def inquiry (self): return
  "name={}, balance={}". Format (Self.name, self.balance)
 
 @ Staticmethod
 def type (): Return ' current account
  '
 
>>> account.deposit
<unbound Method account.deposit>
>>> account.type
<function type at 0x106893668>

Use the @staticmethod adorner to define static methods that do not require the self parameter. Static methods can better organize code related to classes, or they can be overridden in subclasses.
class Method

Class methods are called by the class itself, not by an instance. Class method uses the @classmethod adorner definition, as the first parameter is passed to the method by the class rather than the instance.

Import JSON
 
class account (object):
 num_accounts = 0
 
 def __init__ (self, Name, balance):
  self.name = name
  self.balance = Balance
  Account.num_accounts + 1
 
 def del_account (self):
  account.num_accounts-= 1
 
 def deposit (Self, AMT):
  Self.balance = Self.balance + amt
 
 def withdraw (self, AMT):
  self.balance = Self.balance-amt
 
 def inquiry (s ELF): Return
  "name={}, balance={}". Format (Self.name, self.balance)
 
 @classmethod
 def from_json (CLS, Params_json):
    params = json.loads (Params_json) return
  CLS (Params.get ("name"), Params.get ("balance"))
 
 @staticmethod
 def type (): Return ' current account
  '

A common use of class methods is to create a factory as an object. If the account class has many types of data format, such as tuples, JSON strings, and so on. Because the Python class can only define a __init__ method, class methods are convenient in these cases. For example, we want to initialize an account based on a JSON string object, and we define a class factory method From_json, which reads the JSON string object, parses the parameters, and creates the account object based on the parameters. An example of another class instance is the Dict.fromkeys method, which creates a Dict object from a set of keys and value sequences.
Python Special Methods

Sometimes we want to customize the class. This requires changing the way class objects are created and initialized, or providing polymorphic behavior for some operations. Polymorphic behavior allows customization of some python operations, such as +, in the class definition. Python's special methods can do this. These methods are generally __*__ forms, where * represents the method name. such as __init__ and __new__ from defining object creation and initialization, __getitem__, __get__, __add__, __sub__ to simulate Python built-in types, and __getattribute__, __getattr__ And so on to customize the property access. With only a few special methods, we discuss some important special ways to make a simple understanding, and the Python document has a list of all the methods.
special methods for creating objects

The new class instance is created by two-stage procedure, the __new__ method creates a new instance, and __init__ initializes the instance. Users are already familiar with the definition of the __init__ method, but users rarely define the __new__ method, but it is also possible to customize the creation of class instances.
Special methods for property access

We can customize property access to class instances by implementing the following methods.

Class Account (object):
 num_accounts = 0
 
 def __init__ (self, Name, balance):
  self.name = name
  Self.balance = Balance
  account.num_accounts + 1
 
 def del_account (self):
  account.num_accounts-= 1
 
 def __getattr__ (self, name): Return
  "Hey I dont you to called {}". Format (name)
 
 def deposit (Self, AMT): 
   self.balance = Self.balance + amt
 
 def withdraw (self, AMT):
  self.balance = Self.balance-amt
 
 def inquir Y (self): return
  "name={}, balance={}". Format (Self.name, self.balance)
 
 @classmethod
 def from_dict ( CLS, params):
  params_dict = json.loads (params) return
  CLS (Params_dict.get ("name"), Params_dict.get (" Balance ")
 
 @staticmethod
 def type (): Return
  " Current Account "
 
x = Account (' obi ', 0)

__getattr__ (self, name) __: This method is invoked only if name is neither an instance property nor is found in the object's class inheritance chain. This method should return the property value or throw a Attributeerror exception. For example, if X is an instance of the account class, attempting to access a nonexistent property will call this method.

>>> acct = Account ("Obi", "
>>> acct.number
Hey I dont"-any attribute called number

Note If __getattr__ refers to an instance property that does not exist, a dead loop may occur because the __getattr__ method is constantly invoked.

2.__setattr__ (self, name, value) __: This method is invoked when a property assignment occurs. __SETATTR__ will insert the value into the instance property dictionary, rather than using self.name=value, because it will cause a recursive call to the dead loop.

3.__delattr__ (self, name) __:del is called when obj occurs.

4.__getattribute__ (self, name) __: This method is called all the time to implement the property access of the class instance.
special methods of type simulation

For some types, Python defines certain syntax; For example, elements of lists and tuples can be accessed by means of an index notation, which can be added by the + operator, and so on. We can create our own classes that use these special syntaxes, and the Python interpreter will invoke the method we implement when it encounters these special syntaxes. Let's use a simple example below to illustrate this feature, which simulates the basic usage of a Python list.

Class Customlist (object): Def __init__ (self, Container=none): # The class is just a wrapper around another list to # Illustrate special methods if container is None:self.container = [] Else:self.container = Container def  __len__ (self): # Called when a user calls Len (customlist instance) return Len (Self.container) def __getitem__ (self, Index): # Called when a user uses square brackets to indexing return Self.container[index] def __setitem__ (self, Index, value): # Called when a user performs a index assignment if index <= len (self.container): Self.container [index] = value Else:raise indexerror () def __contains__ (self, value): # Called when the user uses the ' in ' key
  Word return value in Self.container def append (self, value): Self.container.append (value) def __repr__ (self): Return Str (self.container) def __add__ (self, Otherlist): # provides support for the ' use of the ' + operator return Cu Stomlist (Self.container+ Otherlist.container)

 

Above, Customlist is a simple wrapper for a real list. We implemented some customization methods to demonstrate:

__len__ (self): Called when the Len () function is invoked on a customlist instance.

>>> myList = customlist ()
>>> mylist.append (1) 
>>> mylist.append (2)
>> > Mylist.append (3)
>>> mylist.append (4)
>>> len (myList)
4

2.__getitem__ (self, Value): Provides bracket indexing usage support for Customlist class instances:

>>> myList = customlist ()
>>> mylist.append (1) 
>>> mylist.append (2)
> >> mylist.append (3)
>>> mylist.append (4)
>>> Mylist[3]
4

3.__setitem__ (self, Key, value): Called when assigning value to Self[key on Customlist class instance.

>>> myList = customlist ()
>>> mylist.append (1) 
>>> mylist.append (2)
>> > Mylist.append (3)
>>> mylist.append (4)
>>> mylist[3] =
4
>>> MYLIST[3]
100

4.__contains__ (self, key): Called when member detection. False if the item is included to return true.

>>> myList = customlist ()
>>> mylist.append (1) 
>>> mylist.append (2)
> >> mylist.append (3)
>>> mylist.append (4)
>>> 4 in myList
True

5.__repr__ (self): Called when the Self is printed with print, the object representation of self is printed.

>>> myList = customlist ()
>>> mylist.append (1) 
>>> mylist.append (2)
> >> mylist.append (3)
>>> mylist.append (4)
>>> print MyList
[1, 2, 3, 4]

6.__add__ (self, otherlist): called using the + operator to compute the addition of two customlist instances.

>>> myList = customlist ()
>>> otherlist = customlist ()
>>> otherlist.append (100)
>>> mylist.append (1) 
>>> mylist.append (2)
>>> mylist.append (3)
> >> Mylist.append (4)
>>> myList + otherlist + otherlist
[1, 2, 3, 4, 100, 100]

The above example demonstrates how to customize a class behavior by defining certain special class methods. You can view a complete list of these custom methods in a Python document. In the next tutorial, we'll put together a special approach to discuss, and explain the descriptor, an important feature that is widely used in Python object-oriented programming.

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.