Python objects and classes and methods

Source: Internet
Author: User
Tags in python


Introduction

This article describes how to integrate functions and data into classes in Python and access them using an object name.


Every piece of data in Python is an object. Each object consists of three parts: ID, data, and type;

The identifier is the object name, and the memory address (Object reference) of the object is also stored. The type specifies the type of the value that the object can store, the data value of the object is saved in a region in the memory;


Everything in python is an object. The so-called object: I am an object myself. The computer I play with is an object, and the chair I sit in is an object, the puppies at home are also an object ......
 
We describe an object by describing attributes (features) and behaviors. For example, the color, size, age, and weight of a home puppy are attributes or characteristics of the puppy. It will scream, shake its tail, and so on.
We describe a real object in two aspects:
What can it do (behavior)
What it is (attributes or features ).
 
In python, the features of an object are also called attributes ). Its behavior is also called method)
Conclusion: Object = Property + method
 
In python, objects with the same attributes and methods are classified as a class)
Such as humans, animals, plants, and so on.
 
A class is the template or blueprint of an object. A class is the abstraction of an object and an object is the instantiation of a class. A class does not represent a specific thing, but an object represents a specific thing.
 
>>> Class people:
... Def speak (self ):
... Print ("hello! ")
...

'''
Defines a people class, defines a speak method, but does not define attributes,
Because the attribute does not belong to a class, it belongs to instances of various classes. That is, it belongs to the object.
Therefore, we can set different attributes for each instance.
'''
>>> Class people: # class
... Def speak (self): # method
... Print ("hello! ")
...
>>>

>>> Jack = people () # Create a jack instance
>>> Tom = people () # Create a tom instance
>>> Import tab # function module for importing table keys
>>> Jack. # Enter jack.. You can see the following method:
Jack. _ class _ jack. _ doc _ jack. _ module _ jack. speak (
>>> Jack. speak () # reference the speak method
Hello!

>>> Jack. age = 39 # Add The age attribute
>>> Jack. height = 120 # add the height attribute
>>> Jack.
Jack. _ class _ jack. _ module _ jack. height
Jack. _ doc _ jack. age jack. speak (
>>> Jack. height
120
>>> Jack. age
39

'''
# Initialization object
When creating a class, you can define a specific method named _ init _ (). You only need to create an instance of this class.
This method will be run. You can pass parameters to the _ init _ () method,
In this way, you can set the attribute as the expected value when creating an object.
The _ init _ () method completes initialization when an object is created,

'''
>>> Class peo:
... Def _ init _ (self, name, age, sex ):
... Self. Name = name
... Self. Age = age
... Self. Sex = sex
... Def speak (self ):
... Print "my name" + self. Name
...
>>>
When instantiating the object of this class:
>>> Zhangsan = peo ("zhangsan", 24, 'man ')
>>> Print zhangsan. Age
24
>>> Print zhangsan. Name
Zhangsan
>>> Print zhangsan. Sex
Man

#----------
>>> Print zhangsan
<__ Main _. peo instance at 0x7fe5041ec248>
'''
To print the print, use the _ str _ method.
The _ str _ () method tells python what content to display when printing an object.
'''
#! /Usr/bin/python
Class peo:
Def _ init _ (self, name, age, sex ):
Self. Name = name
Self. Age = age
Self. Sex = sex
Def speak (self ):
Print "my name" + self. Name
Def _ str _ (self ):
Msg = 'My name is: '+ self. name + "," + "my age is:" + self. age + ',' + "my sex is:" + self. sex
# Msg = 'My name is: '+ self. name + "," + "my age is:" + str (self. age) + ',' + "my sex is:" + self. sex
Return msg
Shanghai = peo ('Shanghai', '23', 'Man ')
# Shanghai = peo ('Shanghai', 23, 'man ')
'''
Msg = 'My name is: '+ self. name + "," + "my age is:" + self. age + ',' + "my sex is:" + self. sex
Here 23 is Age, but it is converted into a string because self. Age defines a string.
If 23 is not escaped, an error is returned.
If you want to escape in the program, you need to use str (self. Age)
'''
Print shanghai

'''
Self is used many times before.
A class is like a blueprint. You can use a class to create multiple object instances,
When the speak () method is called, you must know which object has called it.
Here, the self parameter will tell which object the method is called. This is called instance reference.
Zhangsan. Speak () is like writing peo. speak (zhangsan)
'''

In the above article, the defined strings, lists, dictionaries, and so on are all objects. Each object has some built-in methods, such as using len () for string objects () the method can be used to obtain the length of a string. We can use the dir () method in IDLE to view the methods that an object can use, as shown below:

>>> S = "www.qingsword.com"
>>> Dir (s)
['_ Add _', '_ class _', '_ ins _', '_ delattr __', '_ dir _', '_ doc _', '_ eq _', '_ format _', '_ ge __', '_ getattribute _', '_ getitem _', '_ getnewargs _', '_ gt _', '_ hash __', '_ init _', '_ iter _', '_ le _', '_ len _', '_ lt __', '_ mod _', '_ mul _', '_ ne _', '_ new _', '_ reduce __', '_ performance_ex _', '_ repr _', '_ rmod _', '_ rmul _', '_ setattr __', '_ sizeof _', '_ str _', '_ subclasshook _', 'capitalize', 'casefold', 'center', 'count ', 'enabled', 'enabledwith', 'pandtabs ', 'Find', 'format', 'format _ map', 'index', 'isalnum', 'isalpha ', 'isdecimal ', 'isdigit', 'isidentifier', 'islower', 'isnumeric ', 'isprintable', 'isspace', 'istitle', 'isupload', 'join ', 'ljust ', 'lower', 'lstrip', 'maketrans ', 'Partition', 'replace ', 'rfind', 'rindex', 'Partition UST ', 'rpartition ', 'rsplit ', 'rdstrip', 'Split', 'splits', 'startswith ', 'strip', 'swapcase', 'title', 'translate', 'uppper ', 'zfill']

# All the outputs in the brackets above are separated by commas (,). Each of them is a method that can be used by string objects. The "internal method" with double underscores is used ", an external method is also called an interface function. An internal method is invisible to users, but this does not mean that internal methods cannot be called, when we use the len () function for a string object, we call its internal _ len _ method. We can see from the following example that the outputs of the two are the same.
>>> Print (len (s ))
17
>>> Print (s. _ len __())
17
In fact, when we define a String object, python initializes a str class within it, which contains the built-in methods provided by python for string processing, now this may be a bit unfamiliar. After reading the second paragraph, you will understand the working principles of these internal methods and interface functions after manually creating a class.

0 × 2. How to create a class in python

A class in python is actually a collection of objects and functions that complete a job. When a class is called, it creates an object bound to a name. See the following example, this is a classic example of a refrigerator. Suppose we want to create a class to put the food in the refrigerator, query the food in the refrigerator, and then provide a series of methods to take out the food:

#! /Usr/bin/env python3
# Coding = UTF-8

########
Class Fridge:
"Refrigerator instance """

#--------
Def _ init _ (self, items = {}):
"Class initialization """
If type (items )! = Type ({}):
Raise TypeError ("input parameter error: % s" % items)
Self. items = items
########

# Python uses the class keyword to define a class. This example defines a Fridge class. There is an internal method _ init __in this class, and each class can contain this method, this method can also be excluded. When a Fridge object is initialized by name, the code in the _ init _ function is automatically executed, which is equivalent to the class initialization operation.

# Note the self parameter in the def _ init _ (self, items = {}) section. This is a unique syntax of python. self always represents the class object itself, this initialization code initializes an empty dictionary object. If you do not understand self well, you can try to save self in the code and observe this function. In fact, _ init _ receives a parameter, this parameter must be a dictionary object. If this parameter is omitted, an empty self-dictionary is initialized by default and the dictionary data is saved using the items object in Fridge, however, the self parameter cannot be omitted.

# Now we have a Fridge class. You can use the following method to create an object instance of this class. The following syntax does not pass parameters to Fridge, so an empty dictionary will be initialized, if you want to pass the parameter, you can write p = Fridge ({"apple": 1, "orange": 3}). If so, the items object in Fridge will save the {"apple": 1, "orange": 3} Dictionary.
P = Fridge ()

# Now there is a new object p, which is a complete Fridge class object. During the creation process above, the Fridge class executes the _ init _ method, this creates an empty dictionary object. You can use the class instance name. class object name "access to this data
Print (p. items)

# Output
{}
Now, you can add a series of methods to the Fridge class to provide the necessary functions. Add the following content to the Fridge class to add query or delete food:

#! /Usr/bin/env python3
# Coding = UTF-8

########
Class Fridge:
"Refrigerator instance """

#--------
Def _ init _ (self, items = {}):
"Class initialization """
If type (items )! = Type ({}):
Raise TypeError ("input parameter error: % s" % items)
Self. items = items
   
#--------
Def _ add_multi (self, food_name, quantity ):
"Internal Method: Add a key value to the items Dictionary. If food_name is not in the key list of the items dictionary, it indicates that it is a newly added item and the number is initialized to 0, then add the quantity value passed to this function (which may be one or more )"""
If (not food_name in self. items. keys ()):
Self. items [food_name] = 0
Self. items [food_name] = self. items [food_name] + quantity
   
#--------
Def add_one (self, food_name ):
"Adding a single food to the items dictionary is an interface function that calls the internal method _ add_multi to add food to the refrigerator """
If type (food_name )! = Type (""):
Raise TypeError ("incorrect food Name Type: % s, correct data Type: % s "\
% (Type (food_name), type ("")))
Else:
Self. _ add_multi (food_name, 1)
Return True
   
#--------
Def add_ict (self, food_dict ):
"Like the items dictionary to add multiple foods, this interface function receives a dictionary parameter food_dict and uses the for loop to traverse the key names in the passed Dictionary, then pass the name and quantity to the _ add_multi function """
If type (food_dict )! = Type ({}):
Raise TypeError ("The food name and quantity must use a dictionary. Incorrect data input: % s" % food_dict)
Else:
For food_name in food_dict.keys ():
Self. _ add_multi (food_name, food_dict [food_name])
     
#--------
Def has (self, food_name, quantity = 1 ):
"Check whether there is a food in items. If only one food name is passed to this interface function, quantity is 1 by default. It will call the following has_various function, pass the food name and quantity to determine whether there are so many foods in the refrigerator """
Return self. has_various ({food_name: quantity })
   
#--------
Def has_various (self, foods ):
"Check whether the food is lower than the input value. This interface function accepts an input parameter of the dictionary type and traverses the key name in the input Dictionary, determine whether the value of the corresponding key in the items dictionary of Fridge is less than the value of each food in the passed list. If it is less than, False is returned, which indicates that there are not so many foods in the refrigerator, if the input food name does not exist, a KeyError exception is generated and False "" is returned """
Try:
For food in foods. keys ():
If self. items [food] <foods [food]:
Return False
Return True
Failed T KeyError:
Return False
 
#--------
Def _ get_multi (self, food_name, quantity ):
"Gets out the internal method of the food. This method accepts two values: one is the name of the food, the other is the number of food, and the first if is used to determine whether the food exists in the refrigerator, the second if calls the has () function to pass the food name and quantity to it to determine whether there are so many foods in the refrigerator. if so, the corresponding amount of food is taken out, the third option is to determine whether the food is still in stock after the food is taken out. if the food quantity is 0, delete the food from the dictionary """
If not food_name in self. items. keys ():
Print ("This food is not in the refrigerator: % s, failed to retrieve" % food_name)
Return False
If self. has (food_name, quantity ):
Self. items [food_name]-= quantity
Print ("retrieved successfully: % s, quantity % s" % (food_name, quantity ))
If self. items [food_name] = 0:
Self. items. pop (food_name)
Return True
    
#--------
Def get_one (self, food_name ):
"Fetch a food, call the internal method _ get_multi to retrieve a single food """
If type (food_name )! = Type (""):
Raise TypeError ("incorrect food Name Type: % s, correct data Type: % s "\
% (Type (food_name), type ("")))
Else:
Self. _ get_multi (food_name, 1)
Return True
    
#--------
Def get_evaluate (self, food_dect ):
"Retrieves multiple foods. This function receives a dictionary parameter. The for loop traverses the list of keys in the input Dictionary, then, determine whether the number corresponding to this name in the items dictionary in the Fridge class is greater than or equal to the number set in the imported Dictionary. If the value is true, it indicates that there is enough food in the refrigerator, call _ get_multi to retrieve these foods and their corresponding quantity. If the conditions are not met, the system prompts the user, inventory supplement and existing quantity """
If type (food_dect )! = Type ({}):
Raise TypeError ("The food name and quantity must use a dictionary. Incorrect data input: % s" % food_dict)
For food in food_dect.keys ():
If self. items [food]> = food_dect [food]:
Self. _ get_multi (food, food_dect [food])
Else:
Print ("food: % s, insufficient inventory, current quantity: % s" % (food, self. items [food])
########

# Initialize the Fridge class
P = Fridge ()
Print (p. items)

# Respectively call the add function, such as the Fridge class to add one or more foods
D = {"orange": 5, "apple": 3}
P. add_one ("banana ")
P. add_many (d)
Print (p. items)

# If there is at least one orange in Fridge, retrieve it
If p. has ("orange "):
P. get_one ("orange ")
Print (p. items)
Else:
Print ("There is no orange in the refrigerator ")
 
# If there are five more apple notification users in the refrigerator, if the number of existing apple messages is not output
If p. has ("apple", 5 ):
Print ("at least five apple in the refrigerator ")
Else:
Print ("number of apples in the refrigerator: % s" % p. items ["apple"])

# Determine if there is any dictionary of these foods and quantities in the refrigerator.
If p. has_various ({"apple": 2, "orange": 2, "banana": 1 }):
P. get_many ({"apple": 2, "orange": 2, "banana": 1 })
Print (p. items)

# Because there is only one banana in the refrigerator and it has been taken out just now, it will prompt that this food does not exist.
P. get_one ("banana ")

# I am prompted to stock up because only one apple is in the refrigerator.
P. get_many ({"apple": 3 })
   
# Program output
{}
{'Banana ': 1, 'apple': 3, 'Orange': 5}
Retrieved successfully: orange, quantity 1
{'Banana ': 1, 'apple': 3, 'Orange': 4}
Number of apples in the refrigerator: 3
Retrieved successfully: banana, quantity 1
Retrieved successfully: apple, quantity 2
Retrieved successfully: orange, quantity 2
{'Apple': 1, 'Orange ': 2}
This food does not exist in the refrigerator: banana. Retrieval failed.
Ingredients: apple, insufficient inventory, current quantity: 1

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.