Object-oriented is an abstract thing, the concept is more, the following will be introduced.
I. Classes and instances
Class ( Class
) and instance ( Instance
) are the most important concepts for object-oriented.
A class is a template that is abstracted out. An instance is a concrete "object" created from a class, each with the same method inherited from the class, but the data may be different.
class Student (object): Pass = Student ()
Keyword followed by the class name, the class name is usually the word beginning with the uppercase letter , followed by, indicating which class the class inherits from. class
(object)
In general, if there is no suitable inheriting class, use the object
class, which is the class that all classes will eventually inherit from.
Student is the class name, and Kate is an instance of Student (), and the class can only be used after instantiation.
Second, constructor, destructor, class variable, instance variable
constructor:__init__ (Self,name,age,sex), this method is the constructor, which is called automatically when the instance is instantiated. All if there is a printing method inside this function, the information will be printed when the Kate instance comes out.
__init__
The first parameter of the method is always self
, representing the creation of the instance itself, within the __init__
method, in which various properties can be bound to self
, because self
point to the created instance itself.
With the __init__
method, when you create an instance, you cannot pass in an empty argument, you must pass in a __init__
parameter that matches the method, but it self
does not need to be passed, and the Python interpreter will pass in the instance variable itself.
destructor :__del__ (self), this method is a destructor, which is called automatically when the instance is destroyed.
class variable: country = ' China ', class variable does not need an instance, can be used directly, such as line 14
instance variable: self.name = name, self.name This form is an instance variable that needs to be instantiated before it can be used, such as LINE15 will be error, need to instantiate Line16 Kate, to use name, age, sex
You can freely bind a property to an instance variable, for example, Kate binds a language property to the instance.
Kate.language = ' Chinese ' print (kate.language) #中文
A function defined in a class is only a little different than a normal function, that is, the first argument is always an instance variable, self
and when called, it is not passed. In addition, there is no difference between a class's method and a normal function. For example, the school function only needs to pass city.
Kate.school (' Beijing '# Kate goes to school in Beijing
Here is an example of a specific code snippet.
1 classPerson (object):2Country =' China' #class variables, which do not need to be instantiated, can be used directly3 def __init__(self,name,age,sex):#constructor, instantiated using automatic invocation4Self.name = Name#instance variable, which must be instantiated before it can be used, also called a member variable5Self.age = Age6Self.sex =Sex7 defsay_my_country (self):8 Print(Self.country)#class variables can be used as attributes in a class.9 defSchool (self,city):TenSelf.city = City One Print('%s goes to school at%s'%(self.name,self.city)) A def __del__(self):#destructor , automatically called when the instance is destroyed - Print('automatically called when the instance is destroyed') - Print(Person.country)#class variables, which do not need to be instantiated, can be used directly the #print (person.name) #实例变量, must be instantiated before it can be used, Attributeerror:type object ' person ' has no attribute ' name ' -Kate = Person ('Kate', 18,'female') - Print(Kate.name) - Print(kate.age) + Print(Kate.sex) - Print(Kate.country)# China +Kate.say_my_country ()# China AKate.language ='English' at Print(Kate.language)#English -Kate.school ('Beijing')#Kate goes to school in Beijing
Third, access restrictions
Class
internally, you can have properties and methods, while external code can manipulate data by invoking the method of the instance variable directly, thus hiding the complex logic inside.
1 kate = person (' Kate ', ' female ')2 ' Faye Wong ' 3 Print (Kate.name)
If you add this code line2,kate.name = ' Faye Wong ', then execute line3 will print Faye Wong, not Kate, name will be modified.
Iv. Private variables, private functions, static methods, class methods
private variable:self.__host = host, can only be used in class, if execution Line31 will error Attributeerror: ' Myredis ' object has no attribute ' __host '
Private Function:def __conn_redis (self), can only be used in class, execution line32 will error Attributeerror: ' Myredis ' object has no attribute ' __conn_ Redis
static method: need to add @staticmethod, do not need to instantiate the direct use, in fact, and the class has nothing to do with, is a common function, written in the class, but also can not use self of those things, also can not call other functions in the class
class method: need to add @classmethod, no instantiation can be used directly, it is more advanced than the static method, it can use class variables and class methods, such as function Class_fun (CLS)
1 ImportRedis2 classMyredis ():3Hi='haha'4 def __init__(self,host,db,password="', port=6379):5Self.__host= Host#private variables, which can only be used in classes6SELF.PASSWD =Password7Self.port =Port8Self.db =DB9 #Self.conn_redis ()TenSelf.__conn_redis() One #def Conn_redis (self): A #self.conn = Redis. Redis (Host=self.__host,db=self.db,password=self.passwd,port=self.port) - def __conn_redis(self):#private functions, which can only be used in classes -Self.conn = Redis. Redis (host=self.__host, db=self.db,password=self.passwd,port=self.port) the defGet (self,k): - Print('__host ...', self.__host) - returnSelf.conn.get (k). Decode () - +@staticmethod#Static Methods - defOther (): + Print('I'm the other.') A@classmethod#class method, and does not need to be instantiated, can be used directly, it is more advanced than the static method, it can use class variables and class methods at defClass_fun (CLS): - Print(Cls.hi)#class variables can be called -Cls.class_fun2 ()#class methods can be called - @classmethod - defclass_fun2 (CLS): - Print('class Method 2') in -R = Myredis ('localhost', 3) to #print (r.__host) #AttributeError: ' Myredis ' object has no attribute ' __host ' + #R.__conn_redis () #AttributeError: ' Myredis ' object has no attribute ' __conn_redis ' - Print(R.get ('Kate11')) theMyredis.other ()#static methods do not need to be instantiated *Myredis.class_fun ()
V. Inheritance
In OOP programming, when we define a class, we can inherit from an existing class, and the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base-Class, Super-Class).
For example, we have written a class named Animal, and there is a run () method that can print a word directly, and then create a new Dog
class called, inheriting the Animal
class.
So dog can use the function in the animal class run (), eat (), but also can define their own functions.
@property , this is an adorner that turns the function into a property method, and if the method does not have a parameter, it can become an attribute method.
You can use the b.protectas shown in the code below, instead of adding () Like any other method, such as b.bite ()
1 classAnimal (object):2 defRun (self):3 Print('Running ...')4 defEat (self):5 Print('Eating ...')6 7 classDog (Animal):8 defRun (self):9 Print('Dog is running')Ten defBite (self): One Print('dog would bite people.') A @property - defProtect (self): - Print('dog would protect people.') theA =Animal () - A.run () - a.eat () -b =Dog () + B.run () - b.eat () + B.bite () AB.protect#attribute method, dog would protect people.
Python object-Oriented Programming learning summary