In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of classes and objects in python, which is very detailed and has a certain reference value. Friends who are interested must read it!
Classes and objects
To put it simply, a class is the blueprint and template of an object, and an object is an instance of a class. Although this explanation is a bit like using a concept to explain a concept, we can at least see from this sentence that a class is an abstract concept and an object is a concrete thing. In the world of object-oriented programming, everything is an object, objects have properties and behaviors, each object is unique, and the object must belong to a certain class (type). When we extract static features (attributes) and dynamic features (behaviors) from a large number of objects with common characteristics, we can define something called "class".
Define CLA
In Python, you can use the class keyword to define the class, and then define the method in the class through the previously learned functions, so that you can describe the dynamic characteristics of the object, as shown below.
Class Student (object): # _ _ init__ is a special method for initializing when creating an object # through this method we can bind name and age properties def _ _ init__ (self, name, age): self.name = name self.age = age def study (self, course_name): print (% s is learning% s.'% (self.name) (course_name) # PEP 8 requires identifiers to be concatenated in full lowercase with multiple words with underscores # but many programmers and companies prefer to use hump nomenclature (hump logo) def watch_av (self): if self.age < 18: print (% s can only watch "bear haunts".% self.name) else: print (% s is watching island love action movies.'% self.name)
Description: the functions written in the class are usually called methods, which are the messages that the object can receive.
Create and use objects
After we have defined a class, we can create an object and send a message to it in the following ways.
Def main (): # create student object and specify name and age stu1 = Student ('Luo Hao', 38) # send study message stu1.study ('Python programming') # send watch_av message stu1.watch_av () stu2 = Student ('Wang Dahun', 15) stu2.study ('ideological and moral') stu2.watch_av () if _ name__ = ='_ main__': main ()
Access visibility issu
For the above code, programmers with C++, Java, C#, and other programming experience may ask what access (also known as visibility) we have to the name and age properties bound to the Student object. Because in many object-oriented programming languages, we usually set the properties of the object to private (private) or protected (protected), to put it simply, no outside access is allowed, and the methods of the object are usually public, because the public method is the message that the object can accept. In Python, there are only two types of access to properties and methods, that is, public and private, and if you want the property to be private, you can start with two underscores when naming the property, as the following code can verify.
Class Test: def _ init__ (self, foo): self.__foo = foo def _ bar (self): print (self.__foo) print ('_ bar') def main (): test = Test ('hello') # AttributeError:' Test' object has no attribute'_ bar' test.__bar () # AttributeError: 'Test' object has no attribute' _ foo' print (test.__foo) if _ name__ = "_ _ main__": main ()
However, Python does not strictly guarantee the privacy of private properties or methods, it just changes the name of private properties and methods to "block" access to them, in fact, if you know that the rule of changing names can still access them, the following code can verify this. The reason for this setting can be explained by such a famous saying, that is, "We are all consenting adults here". Because the vast majority of programmers think that openness is better than closure, and programmers are responsible for their own actions.
Class Test: def _ init__ (self, foo): self.__foo = foo def _ _ bar (self): print (self.__foo) print ('_ bar') def main (): test = Test ('hello') test._Test__bar () print (test._Test__foo) if _ name__ = "_ main__": main ()
In actual development, we do not recommend setting the property private, as this will make the subclass inaccessible (as we'll see later). So most Python programmers follow a naming convention that starts with a single underscore to indicate that the property is protected, and code outside this class should be careful when accessing such properties. This practice is not a grammatical rule, and the properties and methods at the beginning of a single underscore are still accessible to the outside world, so more often it is a hint or metaphor.
Object-oriented pillar
Object-oriented has three pillars: encapsulation, inheritance and polymorphism. The last two concepts are described in detail in the next chapter, so let's talk about what encapsulation is. My own understanding of encapsulation is to "hide all the implementation details that can be hidden, and only expose (provide) a simple programming interface to the outside world." The method we define in the class actually encapsulates the data and the operation on the data. after we create the object, we only need to send a message to the object (calling the method) to execute the code in the method. In other words, we only need to know the name of the method and the parameters passed in (the external view of the method), but not the internal implementation details of the method (the internal view of the method).
Practice
Exercise 1: define a class to describe the digital clock
Class Clock (object): "" Digital clock "" def _ _ init__ (self, hour=0, minute=0 Second=0): "" initialization method: param hour: hour: param minute: minutes: param second: seconds "" self._hour = hour self._minute = minute self._second = second def run (self): "Zhaozi"self._second + = 1 if self._second = = 60: self._second = 0 self._minute + = 1 if self._minute = = 60: self._minute = 0 self. _ hour + = 1 if self._hour = = 24: self._hour = 0 def show (self): "display time" return 'dved'%\ (self._hour) " Self._minute, self._second) def main (): clock = Clock (23,59,58) while True: print (clock.show ()) sleep (1) clock.run () if _ _ name__ = ='_ main__': main ()
Exercise 2: define a class to describe a point on the plane and provide a way to move the point and calculate the distance to another point.
From math import sqrtclass Point (object): def _ init__ (self, x, y): "" initialization method: param x: Abscissa: param y: ordinate "self.x = x self.y = y def move_to (self, x) Y): "" move to the specified location: param x: new Abscissa "param y: new ordinate" self.x = x self.y = y def move_by (self, dx, dy): "" move specified increment: param dx: increment of Abscissa "param dy: increment of ordinate"self.x + = dx self.y + = dy def distance_to (self) Other): "" calculate the distance from another point: param other: another point "" dx = self.x-other.x dy = self.y-other.y return sqrt (dx * * 2 + dy * * 2) def _ _ str__ (self): return'(% s,% s)'% (str (self.x), str (self.y)) def main (): P1 = Point (3) 5) p2 = Point () print (p1) print (p2) p2.move_by (- 1,2) print (p2) print (p1.distance_to (p2)) if _ name__ = ='_ main__': main () above are all the contents of the article "sample Analysis of classes and objects in python" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.