8.6 Object-Oriented Programming Fundamentals

Classes and Objects

Simply put, the class is a blueprint and template objects, and objects are instances of classes. Although this explanation was sort of like the concept in the interpretation of the concept, but at least we can see from this statement, the class is an abstract concept, but the object is a specific thing. In object-oriented programming world, everything is an object, the object has attributes and behavior of each object is unique, and the object must belong to a certain category (type). When we put the static characteristic (property) has a lot of common features of objects and dynamic characteristics (behavior) are extracted, you can define a named "class" thing.

Written functions

"" "
Identifies the name of the function ():
a colon will indent a tab
all functions return values in Python, if you do not give return return to the default None, if you give up, it returns the value you give
"" ""
DEF funcName ():
. ....
      return ....
"" "
identifies the class name ():
        there is a colon will indent the Tab
" ""
class className (Object):
        ..... ...

 

 

"" "
1. Import library, Import library name
2. for loop, if the case is counted using
            the start and end not long
    interval range closure is a front and rear opening.
    Range (Start, End, [STEP])
3. Format output
3.1% ->% (), then the integer% d,% f the floating-point connection, the connection string% s.
3.2 {} -> the format (), any type of it can be directly passed, and then formatted output.

4.print console (terminal) Print
4.1 end to end in what way, by default a newline "\ the n-"
4.2 flush flush the buffer.
"" "

 

"" "
Function class can have its own parameters
when you want to share this parameter, then hit the" self "mark.
" ""

class A(object):
       def __init__(self,a):
             self.a = a
       def B(self,b):
             self.b = b
             print(b)
       def C(self):
             print(self.b)


J = A(1000)
J.B(10)
J.C()

 

The definition of class

# Object parameter is not a
"" "
defines a class has only two steps:
1. identifier ClassName class (Object):
2. __init__ rewrite function, but keep in mind, some play on a" self "label
since the latter will learn inheritance, when inheriting the time might have collided case the function name.
or, the class will contain multiple variables, multiple functions, then you need to use the "self" means to differentiate.
3. class the mass participation in the __init__ function to note is that if you are using multiple parameters may be a function of, then.
you just go to define the parameters in the __init__ function
"" "
class Student (Object):
       the __init __ DEF (Self, name):
               # plurality of print "," separated.
               Print (name)


Student(100)

 

 

# This object must be written in Python2, but it can be written in Python3 not write (the default on inherited object).
#
Class Student (object):
      # __init__ is a special method for initialization when you create an object
      # this way we can bind the two properties name and age for students to target
      DEF __init __ (Self, name, age):
            self.name = name
            self.age age =

      Study DEF (Self, COURSE_NAME):
            Print ( '% S is learning% s.'% (self.name, course_name))

      # PEP 8 requires a connection identifier name in all lowercase multiple words with an underscore
      # but many programmers and companies are more inclined to use nomenclature hump (hump logo)
      DEF watch_av (Self):
             IF self.age <18:
                 Print ( '% s can only view "of bears."' the self.name%)
             the else:
                  Print ( '. S% love action movies being viewed island' the self.name%
# instance
student = Student ()

Description : write functions in the class, we usually call a method (the object), the object of these methods is that a message may be received

# Class will learn a little tired.
Class Student (Object):
      "" "
. The second step is initialized, initialize itself
when your class have some common variables, you can initialize
initialize variables are often placed in public.
      " " "
      DEF __init __ (Self, name):
             " ""
             in the class, all variables and functions should mark (Self)
              "" "
              self.name name =
       DEF DEF1 (Self, NUM):
              self.num = NUM
              Print ( self.num)
              Print (the self.name)
       DEF DEF2 (Self):
              Print (self.num)
              Print (the self.name)


the __name__ == IF "__main__":
    # instance, the class name in parentheses "Student ()", directly run the initialization function
     student = Student ( 'Dumiao Miao')
     student.def1 (100)
     student.def2 ()

 

Creating and Using Objects

When we define a good class, you can create objects in the following way and give the object a message.

main DEF ():
      # create student object and specify the names and ages
      stu1 = Student ( 'Luo Hao', 38)
       # Object of study to a message
      stu1.study ( 'Python programming')
       # watch_av send a message to the object
        stu1.watch_av ()
        STU2 Student = ( 'King sledgehammer', 15)
        stu2.study ( 'moral')
        stu2.watch_av ()


if __name__ == '__main__':
       main()

 

Access the visibility problem

For the above code, C ++, Java, C # and other programming experience programmers may ask us to Studenttarget binding nameand ageproperty in the end have the kind of access (also called visibility). Because in many object-oriented programming languages, we will usually target property is set to private (private) or protected (protected), simply put, is not allowed to access the outside world, while the method of the object are usually public ( public), because the disclosed method is that objects accept message. In Python, access the properties and methods of only two, that is, public and private, if you want the property is private property in the name to be used as two underscores beginning, the following code can verify this.

# Private variable before the variable name with "__"
# If you have to use private variables, you can use dir (class ()) to view its real name.
# Private variables / functions can be called directly within the class.
# If you want to reflect a variable / function is particularly important that you can use the "_"

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 guarantee strict privacy private property or method from the grammar, it just gives private properties and methods of a change of name to "hinder" access to them, in fact, if you know the rules can still change the name of access to them, the following code can verify this. The reason for this setting, can be explained by such a famous saying, that "We are all consenting adults here". Because most programmers think better open than closed, and programmers responsible for their own behavior.

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()

 

 

Guess you like

Origin www.cnblogs.com/WANGRUNZE/p/11311407.html