Finally began to learn the basics of object-oriented, object-oriented three major features:
1. Inheritance
2. polymorphic
3. Encapsulation
the world of programs has only two elements: data, algorithms. the algorithm has been trying to change the data and get a new data.
The function of the class is to put the data and algorithms together, which changed the pattern of code, more suitable for people's thinking, so once the launch has been a great development.
Pyhong's class personal feeling is a blend of the idea of objects in JavaScript and the ideas of other languages, and the following examples will simply introduce some basic concepts.
1. Objects can vary in relation to classes, which are properties owned by objects within JavaScript.
class Human (object): Pass def Say_hello (): Print ('hello'= Human () 'Tom' = Say_hello print(tom.age) Tom.say_hello
2. Initialization of objects
Most object-oriented programming languages will have a special method for constructors that initialize objects when they are created. Python is not the same, Python has two such functions, one is the initialization function, one is a constructor, normally, the constructor is almost useless.
So focus on the initialization function, initialization function is also very simple, the name is more special, __init__
ImportMathclassPoint :def __init__(self, x = 0, y =0): Self.move (x, y)defMove (self, x, y): self.x=x self.y=ydefReset (self): self.x=0 Self.y=0defcalculate_distance (self):returnMATH.SQRT (self.x * * 2 + self.y * * 2) Point= Point (3, 4) Print(Point.calculate_distance ())
3. The private nature of the object
Private variables are not supported in Python, but there is a way to make it impossible for clients to call the variable directly: prefix a property with a double underscore so that the property automatically adds the prefix of the previous _classname.
classsecretstring:def __init__(self, plain_string): Self.__plain_string=plain_stringdefget_plain_string (self):returnSelf.__plain_strings= Secretstring ('Hello World') Print('s.get_plain_string =', S.get_plain_string ())Print('s._secretstring.__plain_string =', s._secretstring__plain_string)Print(S.__plain_string)
012:class and Class objects > Preliminary understanding