Object-Oriented programming is a paradigm of the program, which regards the program as a kind of model for the real world, which is called by each other to different objects.
The basic ideas, classes and instances of object-oriented programming. Classes are used to define abstract objects, and instances are created based on the definition of the class.
In Python we use the following method to define a class (according to Python 's programming habit, the class name begins with an uppercase letter, followed by (object), indicating which class the class inherits from. ):
class Python (object): Pass
When we instantiate the method, we use:
xaioming = Python ()
After object-oriented, we're going to set the property.
classperson:def _init__ (self,name):
Self.name = Name
P1=Person () P1.name='Bart'P2=Person () P2.name='Adam'P3=Person () P3.name='Lisa'L1=[P1, p2, p3]l2= Sorted (L1, key=Lambdax:x.name)PrintL2[0].namePrintL2[1].namePrintL2[2].name
The result is:
Adambartlisa
and attributes can be added and reduced like variables .
Both C + + and Java have object-oriented programming, and they all have constructors, and in Python There are things like constructors . That is __init__ (self, property), and the__init__ () method is called automatically when an instance is created.
class Person : def __init__ (Self,name,gender,birth): = name = gender = Birth
The first parameter of the __init__ () method must be self and must be added, and if it is not added, our system will not be able to match the parameters, resulting in a compilation error .
>>>classPerson :def __init__(name):Pass>>> Xiao = person ("Xiao") Traceback (most recent): File"<pyshell#11>", Line 1,inch<module>Xiao= Person ("Xiao") TypeError:__init__() takes 1 positional argument but 2 were given
When we are programming python, we can encapsulate this property in a way if the attributes inside our class do not want to be seen outside.
If an attribute starts with a double underscore (__), the property cannot be accessed externally.
>>>classPerson (object):def __init__(Self,name,score): Self.name=name self.__score=score>>> p = person ('Bob', 59)>>>Print(p.name) Bob>>>Try: Print(p.__score)exceptAttributeerror:Print("Attributeerror") Attributeerror
However, if a property is defined as "__xxx__", then it can be accessed externally, the attribute defined in "__xxx__" is called a special attribute in the Python class, there are many predefined special attributes that can be used, and usually we do not use the common attribute "__xxx__ "Definition.
The attribute "_xxx", which begins with a single underscore, can also be accessed externally, but, by habit, they should not be accessed externally.
Instance Properties Each instance owns and is independent of each other, and the class attribute has only one copy.
Defining class properties can be defined directly in class:
class Person (object): " Earth " def __init__ (self,name): = name print (person.address) Earth>>> p1 = person (' Bob')print (p1.address) Earth
Because Python is a dynamic language, class properties can be added and modified dynamically:
' China ' Print (p1.address) China
When instance properties and class attributes have the same name, the instance property has a high precedence , which masks access to the class properties.
>>> P2 = person ('Dean')print (p2.address)China' Japanese'print (p1.address) Japaneseprint (p2.address) China
Modifying the Class property on the instance is not changing the properties of the class, just adding a new property to the class.
Although private properties cannot be accessed externally, they can be accessed from within the class. In addition to defining the properties of an instance, you can define the methods of the instance.
class people (object): def __init__ (self,name,age): = name self . __age = agedef -get_age (self) :return to self. __age >>> p1 = people ('Dean', +)>>> P1.get_age (16)
Within an instance method, all instance properties can be accessed, so that if the external needs access to private properties, which can be obtained through a method call, the form of the data encapsulation can simplify the external invocation in addition to protecting internal data consistency.
The instance method we define in class is actually a property , which is actually a function object.
>>>classpeople (object):def __init__(self,name,age): Self.name=name self.__age= Agedefget_age (self):returnSelf.__age>>> P1 = People ('Dean', 16)>>>p1.get_age ()16>>>P1.get_age<bound Method People.get_age of <__main__. People object at 0x0354ce10>>
Because the method is also a property, it can also be dynamically added to the instance, just need to use types. Methodtype () turn a function into a method
>>>classpeople (object):def __init__(self,name,age): Self.name=name self.__age= Agedefget_age (self):returnSelf.__age>>>deffn_get_age (self):ifSelf.get_age () >=60: return ' Old' Else: return ' Young'>>> P1 = People ('Dean', 16)>>> P1.term_age =types. Methodtype (FN_GET_AGE,P1)>>>Print(P1.term_age ()) Young
This is the python3.0, if it is 2.0, then we need a different way of writing:
ImportTypesdefFn_get_grade (self):ifSelf.score >= 80: return 'A' ifSelf.score >= 60: return 'B' return 'C'classPerson (object):def __init__(self, Name, score): Self.name=name Self.score=Scorep1= Person ('Bob', 90) P1.get_grade=types. Methodtype (Fn_get_grade, p1, person)PrintP1.get_grade ()#= AP2 = person ('Alice', 65)PrintP2.get_grade ()#error:attributeerror: ' Person ' object with no attribute ' Get_grade '#because the P2 instance is not bound Get_grade
The main difference is our types. Methodtype uses a different method, 3.0 of the version is required two parameters, 2.0 of the version is required three parameters.
Similar to attributes, methods are also divided into instance methods and class methods .
By marking a @classmethod, the method binds to the person class, not to an instance of the class. The first parameter of the class method is passed into the class itself, usually named the parameter name CLS, and the above Cls.count is actually equivalent to person.count.
Because it is called on the class, not on the instance, the class method cannot get any instance variables, only the reference to the class is obtained.
class Person (object): = 0 @classmethod def How_many (CLS): return cls.count def__init__(self, name): = name = person.count + 1 Print= person ('Bob')print person.how_ Many ()
Object-oriented programming for Python