Preliminary Study on the programming method of the Surface object in Python, and the surface object in python
Word exercise
- Class: tells python to create a new thing.
- Object: the most basic thing and any instantiated thing.
- Instance: Create a class to get something.
- Def: Create a function in the class.
- Self: Used in functions in the class. It is a variable that can be accessed by instances and objects.
- Inheritance: inheritance. One class can inherit another class, like you and your parents.
- Composition: A class can contain another class, just like a car contains tires.
- Attribute: An attribute Class, usually including variables.
- Is-a: indicates the inheritance relationship.
- Has-a: Inclusion relationship
Memorizing these words through cards usually makes no sense to separate words, but I still want to know their existence.
Phrase exercises
- Class x (y): Creates a class x that inherits the class y.
- Class x (object): def _ init _ (self, j): class x contains the _ init _ function, which contains Parameters self and j.
- Class x (object): def m (self, j): class x contains m functions. m functions have two parameters: self and j.
- Foo = x (): Set foo to instantiate class x.
- Foo. m (j): Call the m function through foo. The parameters are self and j.
- Foo. k = q: Use foo to assign q to the k attribute.
The above x, y, m, q and so on can be changed.
One reading test
This is a simple script that can be used for exercises. It only needs to download a word list using a urllib library. We will write the following code to the opp_test.py file.
import random from urllib import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class ###(###):": "Make a class named ### that is-a ###.", "class ###(object):\n\tdef __init__(self, ***)" : "class ### has-a __init__ that takes self and *** parameters.", "class ###(object):\n\tdef ***(self, @@@)": "class ### has-a function named *** that takes self and @@@ parameters.", "*** = ###()" : "Set *** to an instance of class ###.", "***.***(@@@)" : "From *** get the *** function, and call it with parameters self, @@@.", "***.*** = '***'": "From *** get the *** attribute and set it to '***'." } PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("###"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] for i in range(0, snippet.count("@@@")): param_count = random.randint(1, 3) param_names.append(', '.join(random.sample(WORDS, param_count))) for sentence in snippet, phrase: result = sentence[:] # fake class names for word in class_names: result = result.replace("###", word, 1) # fake other names for word in other_names: result = result.replace("***", word, 1) # fake parameter lists for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results try: while True: snippets = PHRASES.keys() random.shuffle(snippets) for snippet in snippets: phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print question raw_input("> ") print "ANSWER: %s\n\n" % answer except EOFError: print "\nBye"
Run this example to answer questions as accurately as possible.
root@he-desktop:~/mystuff# python oop_test.py
class Deer(object):def __init__(self, connection)> ANSWER: class Deer has-a __init__ that takes self and connection parameters.class Cause(Agreement):> ANSWER: Make a class named Cause that is-a Agreement.animal.driving(arch)> ANSWER: From animal get the driving function, and call it with parameters self, arch.cat = Aftermath()> ANSWER: Set cat to an instance of class Aftermath.cork.card = 'attempt'>
Class and Object
Class is like a module
You can think of a module as a special dictionary. It can save python code and call it by A. Number. Python also has a structure similar to implementing this purpose, called classes. A class contains many functions and data and can be accessed through.
If I want to write a class similar to mystuff, it is like this:
class mystuff(object): def __int__(self): self.tangerine = "Hello" def apple(self): print "apple"
It is a bit more complicated than a module, but you can think of it as a mini module. What is confusing is that the _ init _ () function and self. tangerine set the value of the tangerine variable.
Here is the reason for using classes to replace modules: You can use the same class in a program for many times. They do not affect each other, but only one module can be imported into a program.
Before understanding this, you must understand what objects are.
The object is like a mini import.
If the class image module is used, the class also has the import function of the Type module. It is instantiation. If you instantiate a class, you get an object.
The method of using a class is similar to calling a function, as shown in the following code:
thing = mystuff()thing.apple()print thing.tangerine
The first step is to instantiate and then call its function. We can use the above Code to analyze how python is executed in order:
- Python looks for Myclass to see if you have defined this class.
- Python creates an empty object for the function defined in the class.
- If there is a magic method _ init __in the class, you will use this function to initialize your empty object.
- There is an extra variable self in the _ init _ method. This is the empty object created by python. You can assign values to this variable.
- In this case, I assigned the lyrics to thing. tangerine and initialized the object.
- Now python can assign this finished object to a variable thing.
This is why we import a class just like calling a function.
Remember, I am not giving a very accurate class working method, just to better understand the class through the module. The fact is that classes and objects and modules are not one thing. To be honest, they are like the following:
- Class is like a blueprint, which is defined to create a mini module.
- Instantiation means that this mini module is used for import at the same time.
- The created mini-module is an object, which is assigned to a variable and then used to work.
- Although it is difficult to transition from a module to a class and an object, this method is better understood.
Extract from something
There are three methods:
# Dictionary mystuff ['apple'] # module mystuff. apple () print mystuff. tangerine # class thing = mystuff () thing. apple () print thing. tangerine
First Class
You may still have a lot of questions. Don't worry. Put these questions into consideration for the moment. Let's take a look at the object-oriented knowledge of our school in the next exercise. Let's take a look at the class Writing Method and prepare for the next exercise.
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song(["they relly around the family", "With pockets full of shells"]) happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
Running result
Happy birthday to youI don't want to get suedSo I'll stop right therethey relly around the familyWith pockets full of shells
Inheritance
You must understand an important concept, that is, the differences between classes and objects. The problem is that there is no real difference between classes and objects. They are the same at different times and I will explain them in Zen:
What is the difference between fish and salmon?
Is this problem dizzy? Sit down and think about it. I mean, the fish and the salmon are different, but they are the same, right? Salmon is a type of fish, so there is no difference. However, salmon is a classification of fish and is different from that of other fish. So salmon and fish are the same and different.
We don't need to really know the difference between salmon and fish, as long as we know that salmon is one of the fish, and there are many other types of fish.
Now let's take a closer look. If you have three salmon and name them Frank, Joe, and Mary, think about this:
What is the difference between Mary and salmon?
This is also a strange problem, but it is simpler than the previous one. You know Mary is a salmon, and she is an instance of a salmon. Joe and Frank are also examples of salmon. But what does the instance mean? That is, they are created in the salmon, and now they are a real thing, the salmon is like their properties.
Now remember: Fish is a class, salmon is a class, and Mary is an object. Think about it. You can understand it.
A fish is a class, that is, a fish is not a real thing, but we instantiate some things through its similar characteristics, such as scale, Gill, and living in water, this is a fish.
Then an expert said, "these fish are salmon. "This expert defines a new category for these fish," salmon ", which has some special properties, long noses, red meat, and lives in the sea. It tastes delicious. Well, it is a salmon.
Finally, a cook came to the experts and said, "No, the salmon you see is here. I call it Mary. I want to make her delicious ." Now you have an instance of salmon (also a fish instance) called Mary. We call this instance an object.
Now we can see that Mary is a salmon and salmon is a fish. The object is a class, and the class is another class.
The code is like this.
This concept is a bit strange, but you only need to pay attention to it when creating and using classes. I will tell you two methods for distinguishing classes and objects.
First, you need to learn the two phrases "is-a" and "has-". Is-a is the association between objects and classes through the class relationship. has-a is the association between objects and classes because they refer to each other.
The following two relationships are used to mark the program below. Remember that the relationship between the fish and the salmon is-a, and the relationship between the salmon and the gill is has-.
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## ?? is-a class Dog(Animal): def __init__(self, name): ## ?? has-a self.name = name ## ?? is-a class Cat(Animal): def __init__(self, name): ## ?? has-a self.name = name ## ?? is-a class Person(object): def __init__(self, name): ## ?? has-a self.name = name ## Person has-a pet of some kind self.pet = None ## ?? has-a class Employee(Person): def __init__(self, name, salary): ## ?? hmm what is this strange magic? super(Employee, self).__init__(name) ## ?? has-a self.salary = salary ## ?? is-a class Fish(object): pass ## ?? is-a class Salmon(Fish): pass ## ?? is-a class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? is-a satan = Cat("Satan") ## ?? is-a mary = Person("Mary") ## ?? is-a mary.pet = satan ## ?? is-a frank = Employee("Frank", 120000) ## ?? is-a frank.pet = rover ## ?? is-a flipper = Fish() ## ?? is-a crouse = Salmon() ## ?? is-a harry = Halibut()
About class Name (object)
I asked you to use class Name (object) but didn't tell you why. For fear of confusion, and do not know how to learn.
There were a lot of problems when designing classes in python at first, and it was too late to find out. They must support such wrong classes. To solve this problem, they must design a new class so that the old class can continue to be used, and the new class can also be used correctly.
This is why the class inherits the object class. Is it a bit confusing? The object here refers to the class, rather than literally interpreting it as an object.
Remember that a new top-level class must inherit objects. Don't worry too much about literal understanding. We need to keep thinking about more important things.
Articles you may be interested in:
- Python uses the object-oriented method to create a thread to implement the 12306 ticket sales system
- In-depth introduction to object-oriented programming in Python
- Briefly describe the concept of object-oriented programming in Python
- Detailed description of object-oriented programming in Python (II)
- Detailed description of object-oriented programming in Python (Part 1)
- Python object-oriented programming class and object learning tutorial
- Python object-oriented ideology Analysis
- Getting started with Python: Object-oriented
- Basic python tutorial-object-oriented concepts
- Access constraints for Python object-oriented members